How to display database content on android Listview? - android

I am working on a contact book like application.I have a database and,I want to display the data in ListView. Can anybody tell me how to achieve this? Below is what I have tried so far,
public class Contacts {
private int id;
private String name;
private String phone_number;
private String email;
public Contacts()
{
}
public Contacts(int id, String name, String phone_number, String email)
{
this.id = id;
this.name = name;
this.phone_number = phone_number;
this.email = email;
}
public Contacts(String name, String phone_number, String email)
{
this.name = name;
this.phone_number = phone_number;
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone_number() {
return phone_number;
}
public void setPhone_number(String phone_number) {
this.phone_number = phone_number;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
}
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_NAME = "ContactsManager";
private static final String TABLE_CONTACTS = "contacts";
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_PH_NO = "phone_number";
private static final String KEY_EMAIL = "email";
public DatabaseHandler(Context context) {
super( context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT," + KEY_EMAIL + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
onCreate(db);
}
public void insertContact(Contacts contacts)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, contacts.getName()); // Contact Name
cv.put(KEY_PH_NO, contacts.getPhone_number()); // Contact Phone
cv.put(KEY_EMAIL, contacts.getEmail()); //Contact Email
// Inserting Row
db.insert(TABLE_CONTACTS, null, cv);
db.close();
}
// Getting All Contacts
public List<Contacts> getAllContacts()
{
List<Contacts> contactList = new ArrayList<Contacts>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst())
{
do {
Contacts contact = new Contacts();
//contact.setId(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhone_number(cursor.getString(2));
contact.setEmail(cursor.getString(3));
// Adding contact to list
contactList.add(contact);
}
while (cursor.moveToNext());
}
// return contact list
return contactList;
}
}
public class View_data extends ListActivity {
DatabaseHandler db = new DatabaseHandler(this);
Cursor c ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_data);
db.getWritableDatabase();
List<Contacts> values = db.getAllContacts();
ArrayAdapter<Contacts> adapter = new ArrayAdapter<Contacts>(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.view_data, menu);
return true;
}
}
In View_data class i tried to display the data but couldn't do it.
Any Suggestion will be highly appreciated.

You have to pass the context ,your list item layout and cursor in the Custom adapter.........
final CustomAdapter adapter = new CustomAdapter(MainActivity.this,
R.layout.listitem, cursor);
list.setAdapter(adapter);
then this is how CustomAdapter class is implemented in which you have to override your bindView method. This will look complex until you study it and then try to do it yourself.
public class CustomAdapter extends CursorAdapter {
// Cursor cursor;
Context context;
public CustomAdapter(Context context, int RId, Cursor cursor) {
super(context, cursor);
// this.cursor = cursor;
this.context = context;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView team1 = (TextView) view.findViewById(R.id.listitem_team1);
team1.setText(cursor.getString(10));
TextView team2 = (TextView) view.findViewById(R.id.listitem_team2);
team2.setText(cursor.getString(11));
TextView date = (TextView) view.findViewById(R.id.listitem_date);
date.setText(cursor.getString(3));
TextView city = (TextView) view.findViewById(R.id.listitem_city);
city.setText(cursor.getString(2));
TextView time = (TextView) view.findViewById(R.id.listitem_time);
time.setText(cursor.getString(4));
TextView ground = (TextView) view.findViewById(R.id.listitem_ground);
date.setText(cursor.getString(1));}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.listitem, parent, false);
return v;
}
}
you can also refer to this link http://dj-android.blogspot.in/2012/10/android-show-data-from-sqlite-db-into.html

You have to pass the data to the UserAdapter.The code
List<DataProvider> data = userDbHelper.getInformation(sqLiteDatabase); is used to retrive data from SQL database which are applied to the variable data. Try this method.
List<DataProvider> data = userDbHelper.getInformation(sqLiteDatabase);
UsersAdapter adapter = new UsersAdapter(this, (ArrayList<DataProvider>) data);
list.setAdapter(adapter);
Then UserAdapter class implentation is given below which extends the ArrayAdapter..
public class UsersAdapter extends ArrayAdapter<DataProvider> {
private static class ViewHolder {
TextView id;
TextView name;
TextView number;
}
public UsersAdapter(Context context, ArrayList<DataProvider> users) {
super(context, R.layout.new_layout, users);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
// User user = getItem(position);
DataProvider dataProvider = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder; // view lookup cache stored in tag
if (convertView == null) {
// If there's no view to re-use, inflate a brand new view for row
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.new_layout, parent, false);
viewHolder.id = (TextView)convertView.findViewById(R.id.textId);
viewHolder.name = (TextView) convertView.findViewById(R.id.textname);
viewHolder.number = (TextView) convertView.findViewById(R.id.textnumber);
// Cache the viewHolder object inside the fresh view
convertView.setTag(viewHolder);
} else {
// View is being recycled, retrieve the viewHolder object from tag
viewHolder = (ViewHolder) convertView.getTag();
}
// Populate the data from the data object via the viewHolder object
// into the template view.
viewHolder.id.setText(dataProvider.getId());
viewHolder.name.setText(dataProvider.getName());
viewHolder.number.setText(dataProvider.getMob());
// Return the completed view to render on screen
return convertView;
}
}
The above code is UserAdapter which extends the ArrayAdapter.Try this method you will get the solution.
You can also refer this link https://github.com/codepath/android_guides/wiki/using-an-arrayadapter-with-listview

Related

Data not being inserted in Table on Button Press

When I tap the button for inserting the data it says it is successful, but when I check my listview there is no data. But If I add again, then only the data is inserted.
Why is the data only inserted on the second time?
Thanks in advance! :D
This is my Database Helper class:
public static final String DB_NAME = "CartDB";
public static final String TABLE_NAME = "Orders";
public static final String COLUMN_ID = "id";
public static final String NAME ="name";
public static final String SIZE ="size";
public static final String QUANTITY ="quantity";
private static final int DB_VERSION = 1;
public cartDatabaseHelper(Context context)
{
super(context,DB_NAME,null,DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE " + TABLE_NAME
+ "(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ NAME + " VARCHAR, "
+ SIZE + " VARCHAR, "
+ QUANTITY + " VARCHAR);";
db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String sql = "DROP TABLE IF EXIST Orders";
db.execSQL(sql);
onCreate(db);
}
public boolean addPerson(String name, String size, String quantity){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(NAME,name);
contentValues.put(SIZE,size);
contentValues.put(QUANTITY,quantity);
long result = db.insert(TABLE_NAME,null ,contentValues);
if(result == -1)
return false;
else
return true;
}
public Cursor getListContents(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
return data;
}
And this is my MainActivity class:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alcohol_list);
db = new cartDatabaseHelper(this);
GridAlcoholAdapter adapter = new GridAlcoholAdapter(alcoholType.this, images, names);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
final int position, long id) {
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = names.get(position);
String size = textSize.getText().toString().trim();
String quantityNumber = textQuantityNumber.getText().toString().trim();
String bottleCase = textBottleCase.getText().toString().trim();
String bottleCaseQuantity = textQuantity.getText().toString().trim();
textQuantity.setText(quantityNumber + " " + bottleCase);
db.addPerson(name,size,bottleCaseQuantity);
dialog.dismiss();
}
});
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Take appropriate action for each action item click
switch (item.getItemId()) {
case R.id.action_cart:
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.cartdialog);
dialog.setTitle("YOUR CART");
listView = (ListView) dialog.findViewById(R.id.listView);
final ListCartAdapter adapter = new ListCartAdapter(alcoholType.this, orderName, orderSize, orderQuantity);
listView.setAdapter(adapter);
Cursor data = db.getListContents();
data.moveToFirst();
while (data.moveToNext()) {
orderName.add(data.getString(1));
orderSize.add(data.getString(2));
orderQuantity.add(data.getString(3));
}
data.close();
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
orderName.clear();
orderSize.clear();
orderQuantity.clear();
}
});
dialog.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
This is my Adapter Class:
public class ListCartAdapter extends BaseAdapter {
private Context context;
private ArrayList<String> orderName;
private ArrayList<String> orderSize;
private ArrayList<String> orderQuantity;
public ListCartAdapter(Context context, ArrayList<String> orderName, ArrayList<String> orderSize, ArrayList<String> orderQuantity){
// public ListCartAdapter(Context context, ArrayList<String> orderName){
this.context = context;
this.orderName = orderName;
this.orderSize = orderSize;
this.orderQuantity = orderQuantity;
}
#Override
public int getCount() {
return orderName.size();
}
#Override
public Object getItem(int position) {
return orderName.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listView;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
listView = inflater.inflate(R.layout.cart_list_item, null);
TextView name = (TextView) listView.findViewById(R.id.textOrderName);
TextView size = (TextView) listView.findViewById(R.id.textOrderSize);
TextView quantity = (TextView) listView.findViewById(R.id.textOrderQuantity);
name.setText(orderName.get(position));
size.setText(orderSize.get(position));
quantity.setText(orderQuantity.get(position));
return listView;
}
Why is the data only inserted on the second time?
The problem is in your while loop. When there is only one order then your while loop body will not be executed because you have used data.moveToNext() as condition. If your order count more than one, only then it will enter into the while loop.
ERROR:
data.moveToFirst();
while (data.moveToNext()) {
orderName.add(data.getString(1));
orderSize.add(data.getString(2));
orderQuantity.add(data.getString(3));
}
SOLUTION:
if(data.moveToFirst())
{
do
{
orderName.add(data.getString(1));
orderSize.add(data.getString(2));
orderQuantity.add(data.getString(3));
} while(data.moveToNext());
}
Hope this will help~
this is happening because you are adding data to orderName,orderSize and orderQuantity after setting adapter to listView. and you are not even calling
adapter.notifyDataSetChanged();
to let the adapter know that dataSet has changed
The problem is that the adapter doesn't know that you have added an element to the database.
After:
db.addPerson(name,size,bottleCaseQuantity);
you should make
adapter.notifyDataSetChanged()
Well guys I fixed the problem
I made a do-while in retrieving the data and it works!
do{
orderName.add(data.getString(1));
orderSize.add(data.getString(2));
orderQuantity.add(data.getString(3));
} while (data.moveToNext());
thanks again to anyone who wanted and helped :D

Alert dialog delete a row on ListView Item click

Good Day Guys..Need some help here..i got troubled from deleting the selected row in my list view..i want to use an alert dialog for confirmation to delete the selected row..and to edit also..i am a beginner and i have tried searching for answers to this problem and also tried relating it to other problems but i still didn't get it...
My DatabaseHelper Class
public class DatabaseHelper extends SQLiteOpenHelper implements Filterable{
// private static final String COLUMN_NAME="ageing_column";
private static final String DATABASE_NAME=" EXPIRATIONMONITORING.DB";
private static final int DATABASE_VERSION = 1;
private static final String CREATE_QUERY =
"CREATE TABLE "+ContractClass.NewInfo.TABLE_NAME+"("+ ContractClass.NewInfo.ITEM_ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+ContractClass.NewInfo.DESCRIPTION+" TEXT, "+
ContractClass.NewInfo.CATEGORY+" TEXT,"+ ContractClass.NewInfo.MONTHONE+" TEXT, "+ ContractClass.NewInfo.REMIND_AT+" TEXT, "+ ContractClass.NewInfo.QTY+" TEXT, "+
ContractClass.NewInfo.LOCATION+" TEXT );";
private SQLiteDatabase sqLiteDatabase;
public DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
//this.context1=context;
Log.e("DATABASE OPERATIONS", "Database created / opened....");
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_QUERY);
Log.e("DATABASE OPERATIONS", "Table created....");
}
public void addInformations(String description, String category, String monthOne,String quantity,String remind, String location, SQLiteDatabase db)
{
ContentValues contentValues=new ContentValues();
contentValues.put(ContractClass.NewInfo.LOCATION,location);
contentValues.put(ContractClass.NewInfo.DESCRIPTION,description);
contentValues.put(ContractClass.NewInfo.CATEGORY,category);
contentValues.put(ContractClass.NewInfo.MONTHONE,monthOne);
contentValues.put(ContractClass.NewInfo.REMIND_AT,remind);
contentValues.put(ContractClass.NewInfo.QTY,quantity);
db.insert(ContractClass.NewInfo.TABLE_NAME, null, contentValues);
Log.e("DATABASE OPERATIONS", "One row inserted");
db.close();
}
public Cursor getInformations(SQLiteDatabase db)
{
Cursor cursor;
String[] projections ={ContractClass.NewInfo.DESCRIPTION,ContractClass.NewInfo.CATEGORY,ContractClass.NewInfo.MONTHONE, ContractClass.NewInfo.QTY, ContractClass.NewInfo.REMIND_AT,ContractClass.NewInfo.LOCATION};
cursor=db.query(ContractClass.NewInfo.TABLE_NAME, projections, null, null, null, null, null);
return cursor;
}
public Cursor getContact(String location,SQLiteDatabase sqLiteDatabase)
{
String[] projections ={ContractClass.NewInfo.DESCRIPTION,ContractClass.NewInfo.CATEGORY,ContractClass.NewInfo.MONTHONE, ContractClass.NewInfo.QTY, ContractClass.NewInfo.REMIND_AT,ContractClass.NewInfo.LOCATION};
String selection = ContractClass.NewInfo.LOCATION+" LIKE? ";
String [] sargs={location};
Cursor cursor=sqLiteDatabase.query(ContractClass.NewInfo.TABLE_NAME,projections,selection,sargs,null,null,null);
return cursor;
}
public String[] SelectAllData()
{
try
{
String arrData[]=null;
SQLiteDatabase db;
db=this.getReadableDatabase();
String strSQL=" SELECT "+ ContractClass.NewInfo.LOCATION+" FROM "+ ContractClass.NewInfo.TABLE_NAME;
Cursor cursor =db.rawQuery(strSQL,null);
if(cursor !=null)
{
if(cursor.moveToFirst())
{
arrData=new String[cursor.getCount()];
int i=0;
do
{
arrData[i]=cursor.getString(0);
i++;
}while(cursor.moveToNext());
}
}
cursor.close();
return arrData;
}catch(Exception e){
return null;
}
}
public void delete_byID(int id){
sqLiteDatabase.delete(ContractClass.NewInfo.TABLE_NAME, ContractClass.NewInfo.ITEM_ID + "=" + id, null);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
#Override
public Filter getFilter() {
return null;
}
}
THis is My MAin Class..
public class ViewListsActivity extends AppCompatActivity {
DatabaseHelper databaseHelper;
SQLiteDatabase sqLiteDatabase;
ListDataAdapter listDataAdapter;
ListView listView;
Cursor cursor;
EditText delete_txt;
String deletetxt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_lists_activity);
listView = (ListView) findViewById(R.id.search_listView);
listDataAdapter = new
ListDataAdapter(getApplicationContext(),R.layout.row_layout);
databaseHelper = new DatabaseHelper(getApplicationContext());
databaseHelper = new DatabaseHelper(this);
delete_txt = (EditText) findViewById(R.id.delete_text);
sqLiteDatabase = databaseHelper.getReadableDatabase();
cursor = databaseHelper.getInformations(sqLiteDatabase);
listView.setAdapter(listDataAdapter);
if (cursor.moveToFirst()) {
do {
String description, category, month1,remind,qty,location;
description = cursor.getString(0);
category = cursor.getString(1);
month1 = cursor.getString(2);
qty=cursor.getString(3);
remind=cursor.getString(4);
location = cursor.getString(5);
DataProvider dataProvider = new DataProvider(description,
category, month1,qty,remind,location);
listDataAdapter.add(dataProvider);
} while (cursor.moveToNext());
}
listView.setOnItemLongClickListener(new
AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View
view, int position, long id) {
return false;
}
});
}
public void ToSearchBtn(View view)
{
Intent intent=new Intent(this,ThirdActivitySearchAllData.class);
startActivity(intent);
}
public void ToAddNewItemBtn(View view)
{
Intent intent=new Intent(this,SecondActivitySaveData.class);
startActivity(intent);
}
}
My List Adapter Class
public class ListDataAdapter extends ArrayAdapter {
List list = new ArrayList();
public ListDataAdapter(Context context, int resource) {
super(context, resource);
}
static class LayoutHandler
{
TextView DESCRIPTION,CATEGORY,MONTH1,QTY,REMIND,LOCATION;
}
public void add(Object object)
{
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row =convertView;
LayoutHandler layoutHandler;
if(row==null)
{
LayoutInflater layoutInflater=(LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row=layoutInflater.inflate(R.layout.row_layout,parent,false);
layoutHandler=new LayoutHandler();
layoutHandler.DESCRIPTION= (TextView) row.findViewById(R.id.text_description);
layoutHandler.CATEGORY= (TextView) row.findViewById(R.id.text_category);
layoutHandler.MONTH1= (TextView) row.findViewById(R.id.text_monthOne);
layoutHandler.REMIND= (TextView) row.findViewById(R.id.text_remind);
layoutHandler.QTY= (TextView) row.findViewById(R.id.text_qty);
layoutHandler.LOCATION= (TextView) row.findViewById(R.id.text_location);
row.setTag(layoutHandler);
}else
{
layoutHandler=(LayoutHandler)row.getTag();
}
DataProvider dataProvider= (DataProvider) this.getItem(position);
layoutHandler.DESCRIPTION.setText(dataProvider.getDescription());
layoutHandler.CATEGORY.setText(dataProvider.getCategory());
layoutHandler.MONTH1.setText(dataProvider.getMonthOne());
layoutHandler.REMIND.setText(dataProvider.getRemindAt());
layoutHandler.QTY.setText(dataProvider.getQuantity());
layoutHandler.LOCATION.setText(dataProvider.getLocation());
return row;
}
}
You can use ALERT DIALOG for showing confirmation popup, with YES/NO option both for delete and edit, and based on options selected in ALERT DIALOG you can perform further operations
In the below link you can find the sample code
How do I display an alert dialog on Android?

Android Checkbox with Listview and SQLite

I have created an application that a user can store player information. I am now looking to have a checkbox to confirm that the player is available. I know that sqlite cannot store a boolean value so was wondering if someone could help me with a way around this. I have added the checkbox but at the moment i have it stored as a 0 value with no functionality.
Below is the display adapter:
public class DisplayAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<String> id;
private ArrayList<String> firstName;
private ArrayList<String> lastName;
private ArrayList<String> Email;
//private ArrayList<String> ConFirm;
public DisplayAdapter(Context c, ArrayList<String> id,ArrayList<String> fname, ArrayList<String> lname, ArrayList<String> email, ArrayList<String> check) {
this.mContext = c;
this.id = id;
this.firstName = fname;
this.lastName = lname;
this.Email = email;
this.ConFirm = check;
}
public int getCount() {
// TODO Auto-generated method stub
return id.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView(int pos, View child, ViewGroup parent) {
Holder mHolder;
LayoutInflater layoutInflater;
if (child == null) {
layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.listcell, null);
mHolder = new Holder();
mHolder.txt_id = (TextView) child.findViewById(R.id.txt_id);
mHolder.txt_fName = (TextView) child.findViewById(R.id.txt_fName);
mHolder.txt_lName = (TextView) child.findViewById(R.id.txt_lName);
mHolder.txt_eMail = (TextView) child.findViewById(R.id.txt_eMail);
mHolder.txt_cOnfirm = (CheckBox) child.findViewById(R.id.txt_cOnfirm);
child.setTag(mHolder);
} else {
mHolder = (Holder) child.getTag();
}
mHolder.txt_id.setText(id.get(pos));
mHolder.txt_fName.setText(firstName.get(pos));
mHolder.txt_lName.setText(lastName.get(pos));
mHolder.txt_eMail.setText(Email.get(pos));
return child;
}
public class Holder {
TextView txt_id;
TextView txt_fName;
TextView txt_lName;
TextView txt_eMail;
CheckBox txt_cOnfirm;
}
}
Here is the display call from the main activity:
private void displayData() {
dataBase = mHelper.getWritableDatabase();
Cursor mCursor = dataBase.rawQuery("SELECT * FROM "
+ DbHelper.TABLE_NAME, null);
userId.clear();
user_fName.clear();
user_lName.clear();
user_eMail.clear();
user_cOnfirm.clear();
if (mCursor.moveToFirst()) {
do {
userId.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
user_fName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_FNAME)));
user_lName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_LNAME)));
user_eMail.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_EMAIL)));
user_cOnfirm.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_CONFIRM)));
} while (mCursor.moveToNext());
}
DisplayAdapter disadpt = new DisplayAdapter(getActivity(),userId, user_fName, user_lName, user_eMail, user_cOnfirm);
userList.setAdapter(disadpt);
mCursor.close();
}
{
}
And finally the Dbhelper:
public class DbHelper extends SQLiteOpenHelper {
public static String DATABASE_NAME="userdata";
public static final String TABLE_NAME="user";
public static final String KEY_FNAME="fname";
public static final String KEY_LNAME="lname";
public static final String KEY_EMAIL="email";
public static final String KEY_CONFIRM="confirm";
public static final String KEY_ID="id";
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE="CREATE TABLE " +TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY KEY, "+KEY_FNAME+" TEXT, "+KEY_LNAME+" TEXT, "+KEY_EMAIL+" TEXT, "+KEY_CONFIRM+" TEXT DEFAULT 0)";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
}
If you would like any more information or code just let me know. Thankyou in advance.
------UPDATED------
Below is the db update function from the FoursFragment.java class:
//add
view.findViewById(R.id.btnAdd).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getActivity(),
AddActivity.class);
i.putExtra("update", false);
startActivity(i);
}
});
//Update
userList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Intent i = new Intent(getActivity(),
AddActivity.class);
i.putExtra("Confirm", user_cOnfirm.get(arg2));
i.putExtra("Mail", user_eMail.get(arg2));
i.putExtra("Fname", user_fName.get(arg2));
i.putExtra("Lname", user_lName.get(arg2));
i.putExtra("ID", userId.get(arg2));
i.putExtra("update", true);
startActivity(i);
}
});
//delete
userList.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
final int arg2, long arg3) {
build = new AlertDialog.Builder(getActivity());
build.setTitle("Delete " + user_fName.get(arg2) + " "
+ user_lName.get(arg2) + " " + user_eMail.get(arg2));
build.setMessage("Do you want to delete ?");
build.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
Toast.makeText(
getActivity(),
user_fName.get(arg2) + " "
+ user_lName.get(arg2)
+ " is deleted.", 3000).show();
dataBase.delete(
DbHelper.TABLE_NAME,
DbHelper.KEY_ID + "="
+ userId.get(arg2), null);
displayData();
dialog.cancel();
}
});
build.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
dialog.cancel();
}
});
AlertDialog alert = build.create();
alert.show();
return true;
}
});
return view;
}
}}
#Override
public void onResume() {
displayData();
super.onResume();
}
//display
#SuppressLint("UseValueOf")
private void displayData() {
dataBase = mHelper.getWritableDatabase();
Cursor mCursor = dataBase.rawQuery("SELECT * FROM "
+ DbHelper.TABLE_NAME, null);
userId.clear();
user_fName.clear();
user_lName.clear();
user_eMail.clear();
user_cOnfirm.clear();
if (mCursor.moveToFirst()) {
do {
userId.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
user_fName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_FNAME)));
user_lName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_LNAME)));
user_eMail.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_EMAIL)));
user_cOnfirm.add(new Boolean((mCursor.getInt(mCursor.getColumnIndex(DbHelper.KEY_CONFIRM)) == 1)));
} while (mCursor.moveToNext());
}
DisplayAdapter disadpt = new DisplayAdapter(getActivity(),userId, user_fName, user_lName, user_eMail, user_cOnfirm);
userList.setAdapter(disadpt);
mCursor.close();
}
{
At first you should change your database table. Don't use the type 'TEXT' to store the boolean, use the type 'TINYINT' instead of that. TINYINT provides 1 byte to save the value. Because of that you can define a constraint (the check at the end), to avoid saving values like 3.
String CREATE_TABLE="CREATE TABLE " +TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY KEY, "+KEY_FNAME+" TEXT, "+KEY_LNAME+" TEXT, "+KEY_EMAIL+" TEXT, "+KEY_CONFIRM+" TINYINT DEFAULT 0, check("+KEY_CONFIRM+"=0 OR "+KEY_CONFIRM+"=1)";
To read the value from the database change the loop.
while(mCursor.moveToNext()) {
userId.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
user_fName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_FNAME)));
user_lName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_LNAME)));
user_eMail.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_EMAIL)));
user_cOnfirm.add(new Boolean((mCursor.getInt(mCursor.getColumnIndex(DbHelper.KEY_CONFIRM)) == 1)));
}
You request an Integer instead of a String as returning value from the database. If you need to get a boolean, you can add the comparision with 1.
Just a tip, you don't need your do-while. The cursor points at the beginning on a position before the first entry. With the call of moveToNext for the first time, you move it to the first entry. If there's no entry, the loop will be skipped.
You need to change the type of the ArrayList to Boolean (with a big B).
Add the initialization with the value for the checkbox
mHolder.txt_cOnfirm.setChecked(ConFirm.get(pos));
These are the necessary changes. I add the changed code below (not tested)
public class DisplayAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<String> id;
private ArrayList<String> firstName;
private ArrayList<String> lastName;
private ArrayList<String> Email; // better name it email
private ArrayList<Boolean> ConFirm; //better name it confirm, it's one word
public DisplayAdapter(Context c, ArrayList<String> id,ArrayList<String> fname, ArrayList<String> lname, ArrayList<String> email, ArrayList<String> check) {
this.mContext = c;
this.id = id;
this.firstName = fname;
this.lastName = lname;
this.Email = email;
this.ConFirm = check;
}
public int getCount() {
// TODO Auto-generated method stub
return id.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView(int pos, View child, ViewGroup parent) {
Holder mHolder; // the m shows that this shall be a member variable, this is just local for this method.
LayoutInflater layoutInflater;
if (child == null) {
layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.listcell, null);
mHolder = new Holder();
mHolder.txt_id = (TextView) child.findViewById(R.id.txt_id);
mHolder.txt_fName = (TextView) child.findViewById(R.id.txt_fName);
mHolder.txt_lName = (TextView) child.findViewById(R.id.txt_lName);
mHolder.txt_eMail = (TextView) child.findViewById(R.id.txt_eMail);
mHolder.txt_cOnfirm = (CheckBox) child.findViewById(R.id.txt_cOnfirm);
child.setTag(mHolder);
} else {
mHolder = (Holder) child.getTag();
}
mHolder.txt_id.setText(id.get(pos));
mHolder.txt_fName.setText(firstName.get(pos));
mHolder.txt_lName.setText(lastName.get(pos));
mHolder.txt_eMail.setText(Email.get(pos));
mHolder.txt_cOnfirm.setChecked(ConFirm.get(pos).booleanValue());
return child;
}
public class Holder {
TextView txt_id;
TextView txt_fName;
TextView txt_lName;
TextView txt_eMail;
CheckBox txt_cOnfirm;
}
}
The part from your main activity
private void displayData() {
dataBase = mHelper.getWritableDatabase();
Cursor mCursor = dataBase.rawQuery("SELECT * FROM "
+ DbHelper.TABLE_NAME, null);
userId.clear();
user_fName.clear();
user_lName.clear();
user_eMail.clear();
user_cOnfirm.clear();
while(mCursor.moveToNext()) {
userId.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
user_fName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_FNAME)));
user_lName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_LNAME)));
user_eMail.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_EMAIL)));
user_cOnfirm.add(new Boolean((mCursor.getInt(mCursor.getColumnIndex(DbHelper.KEY_CONFIRM)) == 1)));
}
DisplayAdapter disadpt = new DisplayAdapter(getActivity(),userId, user_fName, user_lName, user_eMail, user_cOnfirm);
userList.setAdapter(disadpt);
mCursor.close();
}
{
}
And your DBHelper
public class DbHelper extends SQLiteOpenHelper {
public static String DATABASE_NAME="userdata";
public static final String TABLE_NAME="user";
public static final String KEY_FNAME="fname";
public static final String KEY_LNAME="lname";
public static final String KEY_EMAIL="email";
public static final String KEY_CONFIRM="confirm";
public static final String KEY_ID="id";
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, 2); // The 2 is the version. It have to be higher than the old, because we changed the database schema
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE="CREATE TABLE " +TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY KEY, "+KEY_FNAME+" TEXT, "+KEY_LNAME+" TEXT, "+KEY_EMAIL+" TEXT, "+KEY_CONFIRM+" TINYINT DEFAULT 0, check("+KEY_CONFIRM+"=0 OR "+KEY_CONFIRM+"=1)";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
}
I hope this solves your problem, if not feel free to ask another question, if please rate this answer as positive.
P.s.:
Take a look at the coding guidelines: https://source.android.com/source/code-style.html

How can i delete selected item from Database and Listview both

I want to delete selected item from listview and Database.
I have write code for List-view and Database insertion.
But problem is with deletion i am using OnItemClick Listener for deletion of particular item.
And for deletion of item i pass Position variable to database delete method.
It work but when you delete upper item of list and than you try to delete lower item it wont delete.
May be because I am passing position variable to database delete method.and in database i am checking it with primary key ID and after deletion of upper item Id of lower item does not change so this problem occurs
suggest me some good solution
Here is code fragment code
public void onStart() {
super.onStart();
initfrag();}
private void initfrag() {
// TODO Auto-generated method stub
dh = new com.myapp.database.DatabaseHelper(getActivity());
nameArray = new ArrayList<String>();
db = new com.myapp.database.DatabaseHelper(getActivity());
list = (ListView)getView().findViewById(R.id.fevlist);
adapter=new ListAdapter(getActivity(), nameArray);
Log.d("Reading: ", "Reading all contacts..");
List<Fevorites> contacts = db.getAllContacts();
for (Fevorites cn : contacts) {
s = "Name: " + cn.getID() + " ,Phone: " + cn.getPhoneNumber()+"\n";
nameArray.add(s);
list.setAdapter(adapter);
}
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView adapterView, View view, int position, long id) {
// TODO Auto-generated method stu
nameArray.remove(position);
Toast t = Toast.makeText(getActivity(), nameArray.get(position), Toast.LENGTH_SHORT);
t.show();
// dh.Deleteitem();
adapter.notifyDataSetChanged();
adapter=new ListAdapter(getActivity(), nameArray);
list.setAdapter(adapter);
}
});
}
Here is Fevorites
public class Fevorites {
//private variables
int _id;
String _name;
String _phone_number;
// Empty constructor
public Fevorites(){
}
// constructor
public Fevorites(int id, String name, String _phone_number){
this._id = id;
this._name = name;
this._phone_number = _phone_number;
}
// constructor
public Fevorites(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;
}
}
Databasehelper class
public DatabaseHelper(Context context) {
super(context,DATABASE_NAME , null,DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_ARTIST + " TEXT,"
+ KEY_SONG + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
public void addContact( ) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ARTIST, "XYZ "); // Contact Name
values.put(KEY_SONG, "XYZ testing "); // Contact Phone
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
public void Deleteitem(String string)
{
SQLiteDatabase db = this.getWritableDatabase();
String query = "DELETE FROM favorite WHERE id="+string;
db.execSQL(query);
}
// Getting All Contacts
public List<Fevorites> getAllContacts() {
List<Fevorites> contactList = new ArrayList<Fevorites>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Fevorites contact = new Fevorites();
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;
}
Fevorites getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_SONG, KEY_ARTIST }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Fevorites contact = new Fevorites(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
// return contact
return contact;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
Here is Custom List adaptor class
*List adapter class *
public class ListAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<String> name;
private static LayoutInflater inflater=null;
public ListAdapter(Activity a, ArrayList<String> nameArray) {
activity = a;
name = nameArray;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return name.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public static class ViewHolder{
public TextView text;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
ViewHolder holder;
if(convertView==null){
vi = inflater.inflate(R.layout.fevorites_list, null);
holder=new ViewHolder();
holder.text=(TextView)vi.findViewById(R.id.list_item_entry_title);
vi.setTag(holder);
}
else
holder=(ViewHolder)vi.getTag();
holder.text.setText(name.get(position));
return vi;
}
}
Normally , you retreive a List of some kind of Objects ( let's say in your case : List of favorites ) , then you pass it to your adapter to display it in a ListView . so your CustomAdapter will be like this :
public class ListAdapter extends BaseAdapter {
private Context context;
private ArrayList<Favorites> items;
private LayoutInflater inflater=null;
public ListAdapter(Context context, ArrayList<Favorites> items) {
this.context = context;
this.items = items;
inflater = LayoutInflater.from(context);
}
public int getCount() {
return items.size();
}
public Favorites getItem(int position) {
return items.get(position);
}
public long getItemId(int position) {
return items.get(position).getId();
}
public static class ViewHolder{
public TextView text;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
ViewHolder holder;
if(convertView==null){
vi = inflater.inflate(R.layout.fevorites_list, parent, false);
holder=new ViewHolder();
holder.text=(TextView)vi.findViewById(R.id.list_item_entry_title);
vi.setTag(holder);
}
else
holder=(ViewHolder)vi.getTag();
holder.text.setText(items.get(position).getName());
return vi;
}
}
and then , instanciate the adapter and pass it to your listView like this :
//retreive the list of contacts
List<Fevorites> contacts = db.getAllContacts();
ListAdapter adapter = new ListAdapter(ActivityName.this , contacts);
list.setAdapter(adapter);
NB : replace the ActivityName by the name of your activity

why does SQLite complain that _id column not found when it's included

I'm developing an Android application (unfortunately) for my coursework. I need to use a SimpleCursorAdapter to display a custom ListView of appointments. The constructor of the SimpleCursorAdapter takes a cursor as a parameter and this cursor needs to select all the columns that need to be displayed in the listView.
My problem is that everytime I run the application, it complains that: 'column '_id' does not exist' but there is a column called id! Where am I going wrong?
Below is the relevant code:
public class AppointmentsDB {
public static final String DATABASE_NAME = "appointment_db";
public static final String DATABASE_TABLE = "appointment_table";
private static final int DATABASE_VERSION = 1;
public static final String KEY_ID = "_id";
public static final String KEY_TITLE = "title";
public static final String KEY_DESCRIPTION = "description";
public static final String KEY_PRIORITY = "priority";
public static final String KEY_DATE_TIME = "date_time";
public static final String KEY_DURATION = "duration";
public static final String KEY_ALARM_TIME = "alarm_time";
private DatabaseHelper appointmentsDBHelper;
private SQLiteDatabase appointmentsDB;
private final Context context;
public AppointmentsDB(Context context) {
this.context = context;
appointmentsDBHelper = new DatabaseHelper(context);
}
public SQLiteDatabase openReadableDatabase()
{
return appointmentsDBHelper.getReadableDatabase();
}
public SQLiteDatabase openWritableDatabase()
{
return appointmentsDBHelper.getWritableDatabase();
}
public long addAppointment(Appointment appointment)
{
//
}
public void close()
{
//
}
static class DatabaseHelper extends SQLiteOpenHelper {
Context context;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
StringBuilder query = new StringBuilder();
query.append("CREATE TABLE "+DATABASE_TABLE+" ");
query.append("(");
query.append(KEY_ID+" INTEGER PRIMARY KEY AUTOINCREMENT, ");
query.append(KEY_TITLE+" TEXT NOT NULL, ");
query.append(KEY_DESCRIPTION+" TEXT, ");
query.append(KEY_PRIORITY+" INTEGER, ");
query.append(KEY_DATE_TIME+" INTEGER, ");
query.append(KEY_DURATION+" INTEGER, ");
query.append(KEY_ALARM_TIME+" INTEGER");
query.append(");");
ContentValues test = new ContentValues();
db.execSQL(query.toString());
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+DATABASE_TABLE);
onCreate(db);
}
}
}
MainActivity.java
public class MainActivity extends ListActivity {
private Cursor cursor;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AppointmentsDB dbHelper = new AppointmentsDB(this);
// Execute query that selects all appointments.
// Store cursor from that query in local variable 'cursor'.
// Pass 'cursor' to SimpleCursorAdapter.
// SimpleCursorAdapter uses 'cursor' to display all appointments in
// listview.
StringBuilder selectQuery = new StringBuilder();
selectQuery.append("SELECT "+AppointmentsDB.KEY_ID+" ,");
selectQuery.append(AppointmentsDB.KEY_TITLE + ", ");
selectQuery.append(AppointmentsDB.KEY_DESCRIPTION + ", ");
selectQuery.append(AppointmentsDB.KEY_PRIORITY + ", ");
selectQuery.append(AppointmentsDB.KEY_DATE_TIME + ", ");
selectQuery.append(AppointmentsDB.KEY_DURATION + ", ");
selectQuery.append(AppointmentsDB.KEY_ALARM_TIME + " FROM "
+ AppointmentsDB.DATABASE_TABLE /*+ " "*/);
selectQuery.append("ORDER BY " + AppointmentsDB.KEY_DATE_TIME
+ " ASC");
cursor = dbHelper.openReadableDatabase().rawQuery(
selectQuery.toString(), null);
String[] columnNames = new String[]{""};
int[] ids = new int[]{};
AppointmentsCursorAdapter adapter = new AppointmentsCursorAdapter(this,R.layout.row,cursor,columnNames,ids);
this.setListAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
// This class sets our customised layout for the ListView
class AppointmentsCursorAdapter extends SimpleCursorAdapter
{
private Context context;
private int layout;
private int[] colours;
public AppointmentsCursorAdapter(Context context, int layout, Cursor c,
String[] from, int[] to)
{
super(context, layout, c, from, to);
this.context = context;
this.layout = layout;
//...
}
public View newView(Context context, Cursor cursor, ViewGroup parent)
{
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(layout, parent, false);
TextView titleText = (TextView) view.findViewById(R.id.titleText);
TextView priorityView = (TextView) view.findViewById(R.id.priorityView);
TextView dateText = (TextView) view.findViewById(R.id.dateText);
TextView monthText = (TextView) view.findViewById(R.id.monthText);
TextView timeText = (TextView) view.findViewById(R.id.timeText);
//...
return view;
}
#Override
public void bindView(View view, Context context, Cursor cursor)
{
super.bindView(view, context, cursor);
TextView titleText = (TextView) view.findViewById(R.id.titleText);
TextView priorityView = (TextView) view.findViewById(R.id.priorityView);
TextView dateText = (TextView) view.findViewById(R.id.dateText);
TextView monthText = (TextView) view.findViewById(R.id.monthText);
TextView timeText = (TextView) view.findViewById(R.id.timeText);
//...
}
}
}
rename the column to id and change the select statement to: "SELECT "+AppointmentsDB.KEY_ID+" AS _id ,"
Try this:
String[] columnNames = new String[]{AppointmentsDB.KEY_ID};
int[] ids = new int[]{R.id.the_id_of_the_edittext_textview_or_wahtever_you_use_in_row_layout};
Also, unlesss you want to do fancy things, maybe you can simply use a SimpleCursorAdapter like this:
ListAdapter adapter = new SimpleCursorAdapter(this, R.layout.row, cursor, columnNames, ids, CursorAdapter.NO_SELECTION);
setListAdapter(adapter);
I would also recommend using a ListFragment instead of ListActivity so you can reuse the list in other activities or situations (tablets...) if needed.

Categories

Resources