I have an SQLite database that has the columns ID, Homework, Classname, date. I also have an expandable listview. My code works and creates an expandable listview however it duplicates the group titles.
The group names are from the classname column, and the child objects are added to the group with the same classname. However the expandable listview takes each classname when I really need it to take each unique classname so that it doesn't duplicate the groups. Here is my expandable listview adapter:
public class ExpandListAdapter extends CursorTreeAdapter {
SQLiteHelper values;
private LayoutInflater mInflator;
Context context;
TextView groupHeader;
public ExpandListAdapter(Cursor cursor, Context context){
super(cursor, context);
this.context = context;
values = new SQLiteHelper(context);
mInflator = LayoutInflater.from(context);
}
#Override
public View newGroupView(Context context, Cursor cursor, boolean isExpanded,
ViewGroup parent){
final View view = mInflator.inflate(R.layout.group_header, parent, false);
return view;
}
public void bindGroupView(View view, Context context, Cursor cursor, boolean isExpanded){
groupHeader = (TextView) view.findViewById(R.id.group_name);
if(groupHeader != null){
groupHeader.setText(cursor.getString(cursor.getColumnIndex("class")));
}
}
#Override
public View newChildView(Context context, Cursor cursor,
boolean isLastChild, ViewGroup parent){
final View view = mInflator.inflate(R.layout.row_expandable, parent, false);
return view;
}
#Override
public void bindChildView(View view, final Context context, final Cursor cursor,
boolean isLastChild){
TextView homework = (TextView) view.findViewById(R.id.homeworkDisplay1);
if(homework != null){
homework.setText(cursor.getString(cursor.getColumnIndex(values.KEY_HOMEWORK)));
}
TextView date = (TextView) view.findViewById(R.id.dueDisplay1);
if(date != null){
date.setText(cursor.getString(cursor.getColumnIndex(values.KEY_DATE)));
}
TextView classes = (TextView) view.findViewById(R.id.classDisplay1);
if(classes != null){
classes.setText(cursor.getString(cursor.getColumnIndex(values.KEY_CLASS)));
}
}
#Override
protected Cursor getChildrenCursor(Cursor groupCursor){
values.open();
Cursor childCursor = values.fetchChildren(groupCursor.getString(groupCursor.getColumnIndex("class")));
childCursor.moveToFirst();
values.close();
return childCursor;
}
#Override
public void onGroupCollapsed(int groupPosition){
}
#Override
public void onGroupExpanded(int groupPosition){
}
}
and here is my SQLitehelper class:
public class SQLiteHelper{
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "homeworkManager";
public static final String TABLE_NAME = "homeworkList";
public static final String KEY_ID = "_id";
public static final String KEY_HOMEWORK = "homework";
public static final String KEY_DATE = "date";
public static final String KEY_CLASS = "class";
private SQLiteDatabase db;
private DblistHelper myHelper;
Cursor DB_Cursor;
Context context;
class DblistHelper extends SQLiteOpenHelper {
public DblistHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE = "Create table " + TABLE_NAME + " ("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_HOMEWORK + " TEXT ,"
+ KEY_DATE + " TEXT ,"
+ KEY_CLASS + " TEXT)";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
public SQLiteHelper(Context context){
this.context = context;
}
public SQLiteHelper open() throws SQLException{
myHelper = new DblistHelper(context);
db = myHelper.getReadableDatabase();
return this;
}
public void close(){
if(myHelper != null){
myHelper.close();
}
}
public long insertData(String homework, String data, String classes){
ContentValues values = new ContentValues();
values.put(KEY_HOMEWORK, homework);
values.put(KEY_DATE, data);
values.put(KEY_CLASS, classes);
return db.insert(TABLE_NAME, null, values);
}
public Cursor fetchGroup(){
String query = "SELECT * FROM homeworkList";
return db.rawQuery(query, null);
}
public Cursor fetchChildren(String class_name){
String query = "SELECT * FROM homeworkList WHERE class = '" + class_name + "'";
Cursor cursor = db.rawQuery(query, null);
return cursor;
}
public void remove(long id){
String whereClause = "_id=?";
String[] whereArgs = new String[]{String.valueOf(id)};
db.delete(TABLE_NAME, whereClause, whereArgs);
}
}
Thanks in advance :)
Hi there instead of passing the Cursor from this constructor
public ExpandListAdapter(Cursor cursor, Context context){
why not just replace it with a List intended for your ListView
public ExpandListAdapter(Context context, List parent, List child){
so that you wont have to fetch data in every view also to prevent data being duplicated
Related
Can anyone show me how to delete contents from an SQLite database and listview by long clicking on it? Also, do I have to delete only contents from SQLite database or from both SQLite database and listview?
Here are my project classes:
Database Helper
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 3;
private static final String DATABASE_NAME = "products.db";
private static final String TABLE_NAME = "products";
private static final String COLUMN_ID = "_id";
private static final String MARKET = "market";
private static final String PRODUCT = "product";
private SQLiteDatabase db;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ MARKET + " TEXT, "
+ PRODUCT + " TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME + "");
onCreate(db);
}
public Cursor getRecords() {
db = getReadableDatabase();
return db.rawQuery(
"SELECT * FROM " + TABLE_NAME,
null);
}
public void addRecords(String market, String product) {
db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(MARKET, market);
contentValues.put(PRODUCT, product);
db.insert(TABLE_NAME, null, contentValues);
db.close();
}
public void deleteRecords(int id){
}}
MainActivity
public class MainActivity extends AppCompatActivity {
ListView lv;
DatabaseHelper databaseHelper;
ShoppingCartAdapter shoppingCartAdapter;
private static final int TIME_ENTRY_REQUEST_CODE = 1;
Cursor cursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.list_view_main);
databaseHelper = new DatabaseHelper(this);
ListView listView = (ListView) findViewById(R.id.list_view_main);
shoppingCartAdapter = new ShoppingCartAdapter(this, databaseHelper.getRecords(), CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
listView.setAdapter(shoppingCartAdapter);
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(final AdapterView<?> parent, View view, int position, long id) {
final int pos = position;
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Are you sure you want to delete?");
builder.setPositiveButton("DELETE", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder.setNegativeButton("CANCEL", null);
builder.show();
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu_template, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.menu_add_id) {
Intent intent = new Intent(this, AddContentActivity.class);
startActivityForResult(intent, TIME_ENTRY_REQUEST_CODE);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == TIME_ENTRY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
String market = data.getStringExtra("market");
String product = data.getStringExtra("product");
databaseHelper.addRecords(market, product);
shoppingCartAdapter.changeCursor(databaseHelper.getRecords());
}
}
}
}
AddContentActivity
public class AddContentActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addcontent);
}
public void onAddButton(View view){
Intent intent = getIntent();
EditText marketet = (EditText) findViewById(R.id.marketet_id);
EditText productet = (EditText) findViewById(R.id.productet_id);
intent.putExtra("market", marketet.getText().toString());
intent.putExtra("product", productet.getText().toString());
this.setResult(RESULT_OK, intent);
finish();
}
}
ShoppingCartAdapter
public class ShoppingCartAdapter extends CursorAdapter{
public ShoppingCartAdapter(Context context, Cursor cursor, int flags){
super(context, cursor, flags);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView marketTv = (TextView) view.findViewById(R.id.markettv_id);
TextView productTv = (TextView) view.findViewById(R.id.producttv_id);
marketTv.setText(cursor.getString(1));
productTv.setText(cursor.getString(2));
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.list_view_template, parent, false);
return view;
}
}
After couple of days I found solution on my question.If there is better way of doing delete, please post answer.
I added following lines of code:
Main Activity
Cursor cursor = (Cursor) parent.getItemAtPosition(pos);
final int item_id = cursor.getInt(cursor.getColumnIndex("_id"));
databaseHelper.deleteRecords(item_id );
cursor.requery();
DatabaseHelper
public void deleteRecords(int id){
db.delete(TABLE_NAME, COLUMN_ID + "=" + id, null);
}
EDIT:
replaced cursor.requery(); with
shoppingCartAdapter.changeCursor(databaseHelper.getRecords());
because using requery(); is deprecated but both lines of code work.
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?
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
I have faced some problems when I want to retrive data from db to some textviews and then put those textvies into a listview.Let me explain I have two columns like date and head in my database.And I want to retrieve those into their each textviews and put these textvies into a listview.I know this may be a silly question for others,but i am new in this field.i know something about SimpleCursorAdapter but dont know how to and where to use it.It may be solve through this.So please guide me.
My Classes::I have created a DBAdapter class for database.MyArrayAdapter class. And a main class calles as Head.java.
DBAdapter.java
public class DBAdapter {
//EditText mHead;
public static final String KEY_ROWID="_id";
public static final String KEY_DATE="date";
public static final String KEY_HEAD="head";
private static final String TAG="DBAdapter";
private static final String DATABASE_NAME="accounting";
private static final String DATABASE_TABLE="accounts";
private static final int DATABASE_VERSION=1;
private static final String DATABASE_CREATE=
"create table accounts (_id integer primary key autoincrement," +
"date datetime not null, head text not null);";
private final Context context;
private DataBaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx){
this.context=ctx;
DBHelper=new DataBaseHelper(context);
}
private static class DataBaseHelper extends SQLiteOpenHelper {
DataBaseHelper(Context context){
super(context,DATABASE_NAME,null,DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
try {
db.execSQL(DATABASE_CREATE);
}catch(SQLException e){
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
Log.w(TAG, "Updrading database from version "+oldVersion+" to "+newVersion+"," +
"which will destroy all old data");
db.execSQL("drop table if exists accounts");
onCreate(db);
}
}
public DBAdapter open() throws SQLException{
db=DBHelper.getWritableDatabase();
return this;
}
public void close(){
DBHelper.close();
}
**//--insert contact in the database--**
public long insertContact(String date,String head)
{
ContentValues initialvalue=new ContentValues();
initialvalue.put(KEY_DATE, date);
initialvalue.put(KEY_HEAD, head);
return db.insert(DATABASE_TABLE, null, initialvalue);
}
//--delete a particular contact--
public boolean deleteContact(long rowId){
return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null)>0;
}
//--Retrieving all the contacts--
public Cursor getAllContacts(){
return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_DATE,KEY_HEAD}, null, null, null, null,null);
}
//--Retrieve a particular contact--
public Cursor getContact(long rowId)throws SQLException{
Cursor mCursor=
db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,KEY_DATE,KEY_HEAD},
KEY_ROWID + "="+ rowId, null, null, null,
null, null);
if(mCursor != null){
mCursor.moveToFirst();
}
return mCursor;
}
//--update a contact--
public Boolean updateContact(long rowId,String date,String head){
ContentValues args=new ContentValues();
args.put(KEY_DATE, date);
args.put(KEY_HEAD, head);
return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" +rowId,null)>0;
}
}
MyArrayAdapter.java
public class MyArrayAdapter extends ArrayAdapter<Object>{
private final Context context;
private final String[] values;
//#SuppressWarnings("unchecked")
public MyArrayAdapter(Context context,String[] values){
super(context,R.layout.list_things,values);
this.context=context;
this.values=values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
//return super.getView(position, convertView, parent);
LayoutInflater inflate=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowview=inflate.inflate(R.layout.list_things, parent, false);
TextView mDate=(TextView)rowview.findViewById(R.id.tvdate);
TextView mHead=(TextView)rowview.findViewById(R.id.tvhead);
mDate.setText(values[position]);
mHead.setText(values[position]);
return rowview;
}
}
At last the Head class where I want to do all things
Head.java
public class Head extends ListActivity {
String date = "";
String head;
TextView display;
EditText headname;
ListView list;
LayoutInflater inflate;
Layout layout;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.head);
display=(TextView)findViewById(R.id.tvCurrentDate);
display.setText(date);
// Intent intent=new Intent();
DBAdapter db=new DBAdapter(this);
SimpleCursorAdapter adapter=new SimpleCursorAdapter(Head.this, R.layout.list_things, null, null, null);
//Cursor cursor=getContentResolver().query("/data/data/com.crypto.ranjit/DBAdapter",
//new String []{db., selection, selectionArgs, sortOrder)
Bundle b = getIntent().getExtras();
if (b != null) {
date = b.getString("date");
}
Button btnSave = (Button) findViewById(R.id.btnSave);
btnSave.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
headname=(EditText)findViewById(R.id.etHeadname);
date=display.getText().toString();
head=headname.getText().toString();
DBAdapter dba = new DBAdapter(Head.this);
dba.open();
long id = dba.insertContact(date, head);
// id=dba.insertContact(head, date);
dba.close();
}
});
//DBAdapter db=new DBAdapter(Head.this);
//db.open();
}
}
Some silly mistakes here what made me confuse at that time.
Solution:
1:Fill the text views through static values which are define in Head.java.
2:Use ArrayList < HashMap < String, String > > for retrieving data and fill in adapter class.
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.