How to Search value showing wrong index to update and delete in SQLite? - android-studio

Search Function
mSearchView.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
Log.d("data", charSequence.toString());
}
#Override
public void onTextChanged(CharSequence charSequence2, int i, int i1, int i2) {
String select = "SELECT * FROM RECORD WHERE name LIKE '"+charSequence2+"%'";
Cursor cursor = mSQLiteHelper.getData(select);
mList.clear();
while(cursor.moveToNext()) {
int id = cursor.getInt(0);
String name = cursor.getString(1);
String phone = cursor.getString(2);
mList.add(new Model(id,name,phone));
}
mAdapter.notifyDataSetChanged();
}
#Override
public void afterTextChanged(Editable editable) {
}
});
Update: This is LongClickListener where I tap to updated and delete my inserted data
mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long l) {
//Alert dialog to display options of update and delete
final CharSequence [] items = {"Update","Delete","Call"};
AlertDialog.Builder dialog = new AlertDialog.Builder(RecordListActivity.this);
dialog.setTitle("Choose an Action");
dialog.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if(i == 0){
//update
Cursor c = mSQLiteHelper.getData("SELECT id FROM RECORD");
ArrayList<Integer> arrID = new ArrayList<Integer>();
while(c.moveToNext() ){
arrID.add(c.getInt(0));
}
//Show update Dialog
showDialogUpdate(RecordListActivity.this,arrID.get(position));
}
if(i==1){
//delete
Cursor c = mSQLiteHelper.getData("SELECT id FROM RECORD");
ArrayList<Integer> arrID = new ArrayList<Integer>();
while(c.moveToNext()){
arrID.add(c.getInt(0));
}
showDialogDelete(arrID.get(position));
}
//Call try
if(i==2){
TextView tvPhone = view.findViewById(R.id.textphone);
String phone = tvPhone.getText().toString();
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:" + phone));
getBaseContext().startActivity(intent);
}
}
});
dialog.show();
return true;
}
});
Model: This is the Model
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() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
DataBase
public void updateData(String name, String phone, int id){
SQLiteDatabase database = this.getWritableDatabase();
//Query to update record
String sql = "UPDATE RECORD SET name=? , phone=? WHERE id=?";
SQLiteStatement statement = database.compileStatement(sql);
statement.bindString(1,name);
statement.bindString(2,phone);
statement.bindDouble(3,(double)id);
statement.execute();
database.close();
}
//Delete Data
public void deleteData(int id){
SQLiteDatabase database = this.getWritableDatabase();
//query to delete record using id
String sql = "DELETE FROM RECORD WHERE id=?";
SQLiteStatement statement = database.compileStatement(sql);
statement.clearBindings();
statement.bindDouble(1,(double)id);
statement.execute();
database.close();
}
//Getting Data
public Cursor getData(String sql){
SQLiteDatabase database = this.getReadableDatabase();
return database.rawQuery(sql,null);
}
Dialog
//DeleteDialog
private void showDialogDelete(final int idRecord) {
AlertDialog.Builder dialogDelete =new AlertDialog.Builder(RecordListActivity.this);
dialogDelete.setTitle("Warning!!");
dialogDelete.setMessage("Are you sure you want to delete this?");
dialogDelete.setPositiveButton("OK", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialogInterface, int i) {
try{
mSQLiteHelper.deleteData(idRecord);
Toast.makeText(getApplicationContext(), "Delete Successfully", Toast.LENGTH_SHORT).show();
}catch (Exception error){
Log.e("Delete error",error.getMessage());
}
}
});
dialogDelete.setNegativeButton("Cancel",new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
dialogDelete.show();
}
//UpdateDialog
private void showDialogUpdate(Activity activity, int position){
Dialog dialog = new Dialog(activity);
dialog.setContentView(R.layout.update_dialog);
dialog.setTitle("Update");
final EditText updateNameId = dialog.findViewById(R.id.updateNameId);
final EditText updatePhoneId = dialog.findViewById(R.id.updatePhoneId);
final Button updatebuttonId = dialog.findViewById(R.id.updatebuttonId);
//get Data Row Clicked from SQLite
Cursor cursor = mSQLiteHelper.getData("SELECT * FROM RECORD WHERE id="+position);
mList.clear();
while(cursor.moveToNext()){
int id = cursor.getInt(0);
String name = cursor.getString(1);
updateNameId.setText(name);
String phone = cursor.getString(2);
updatePhoneId.setText(phone);
mList.add(new Model(id,name,phone));
}
//set width of dialog
int width = (int)(activity.getResources().getDisplayMetrics().widthPixels * 0.95);
//set height of dialog
int height = (int)(activity.getResources().getDisplayMetrics().heightPixels * 0.7);
dialog.getWindow().setLayout(width,height);
dialog.show();
updatebuttonId.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
try{
mSQLiteHelper.updateData(
updateNameId.getText().toString().trim(),
updatePhoneId.getText().toString().trim(),
position);
dialog.dismiss();
Toast.makeText(getApplicationContext(), "Updated", Toast.LENGTH_SHORT).show();
}catch(Exception error){
Log.e("Update error",error.getMessage());
}
updateRecorderList();
}
});
}
private void updateRecorderList() {
//get all data from SQLite
Cursor cursor = mSQLiteHelper.getData("SELECT * FROM RECORD");
mList.clear();
while(cursor.moveToNext()){
int id = cursor.getInt(0);
String name = cursor.getString(1);
String phone = cursor.getString(2);
mList.add(new Model(id,name,phone));
}
mAdapter.notifyDataSetChanged();
}
When I search any data in the search bar It shows me the searched data but when I click to update it, it shows me the first row data to update, and also when I click to delete it shows me the first row to delete, where is my wrong logic can you enlighten me? anyone

You took the ID incorrectly, because you used a position that was always changing and cannot be correlated with the data.
You do not have to go to the database for the ID, as you already have it:
if (i == 0) {
//update
int contactId = mList.get(position).getId();
showDialogUpdate(RecordListActivity.this, contactId);
}
if (i == 1) {
//delete
int contactId = mList.get(position).getId();
showDialogDelete(contactId);
}

Related

How to delete the item from database and listview by position

I need to delete the item from database and ListView. I can delete the item from ListView but i can't delete it from database. I think the problem is in getting the position of the item from the database i tried to do it in my own but it does not work. I don't know what should I do.Help me to slove this.
myDB = new DbHandler(this);
userList = new ArrayList<>();
data = myDB.getListContents();
numRows = data.getCount();
if (numRows == 0) {
Toast.makeText(AddCount.this, "No Items", Toast.LENGTH_LONG).show();
} else {
while (data.moveToNext()) {
user = new User(data.getString(1), data.getString(2));
userList.add(user);
}
}
adapter = new Two_columnListAdapter(this, R.layout.list_item_layout, userList);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(final AdapterView<?> arg0, View arg1, final int arg2, final long arg3) {
final AlertDialog.Builder delete = new AlertDialog.Builder(AddCount.this);
delete.setIcon(R.drawable.ic_baseline_delete_24);
delete.setTitle("Are you sure");
delete.setMessage("Do you want to delete this item?");
delete.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
DbHandler db = new DbHandler(getApplicationContext());
myDB.deleteData(userList.get(arg2));
userList.remove(arg2);
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Deleted" ,Toast.LENGTH_SHORT).show();
}
});`
`Two_columnAdapter.java
public class Two_columnListAdapter extends ArrayAdapter<User> {
private LayoutInflater layoutInflater;
private ArrayList<User>users;
private int mviewResourceId;
public Two_columnListAdapter(Context context,int textViewResourceId,ArrayList<User>users){
super(context,textViewResourceId,users);
this.users = users;
layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mviewResourceId = textViewResourceId;
}
public View getView(int position, View convertView, ViewGroup parents){
convertView = layoutInflater.inflate(mviewResourceId,null);
User user= users.get(position);
if (user != null){
TextView text = (TextView)convertView.findViewById(R.id.title);
TextView num = (TextView)convertView.findViewById(R.id.value);
if (text != null){
text.setText(user.getText());
}
if (num != null){
num.setText(user.getNum());
}
}
return convertView;
}
DatabaseHelpher(delete the single row from database)
public void deleteData(String id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_Inputs, KEY_ID + " =?", new String[]{id});
db.close();
}
You can save the return data inside a model class instead of a list. Then call the setOnLongClickListener in your adapter class, inside onBindViewHolder.
class listHolder extends RecyclerView.ViewHolder{
private View view;
public listHolder(#NonNull View itemView) {
super(itemView);
view = itemView;
}
}
#Override
public void onBindViewHolder(#NonNull listHolder listHolder, int position, #NonNull userModel userModel) {
viewHolder.view.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// Do somethings....
}
});
For more info you can check out this link, Hope this helps!

How to update RecyclerView in fragment inside TabLayout

I have an activity with tow tabs(with viewPager). inside viewPager is a fragment that have RecyclerView.
first tab is for (Monday-Friday) and second tab is for (Saturday-Sunday)
I want to retrieve data from database and show in recyclerview on each tab. but i cant update my recyclerView. Please help me to do that.And another problem is that when RecyclerView show data only show first row, but the number of rows in the table.like this:
10:06:00
10:06:00
10:06:00
10:06:00
10:06:00
10:06:00
here is my code:
this is my Fragment code:
public class toDastgheybFragment extends BaseFragment {
private List<DatabaseModel> Times = new ArrayList<DatabaseModel>();
DatabaseHelper databaseHelper;
private View mView;
RecyclerView mRecyclerView;
RecyclerView.Adapter mAdapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.fragment_to_dastgheyb, container,
false);
databaseHelper = new DatabaseHelper(getContext());
Times = databaseHelper.getAllUsers();
mRecyclerView = mView.findViewById(R.id.myRecycler);
mAdapter = new DataAdapter(Times);
mRecyclerView.setLayoutManager(new
LinearLayoutManager(getContext()));
mRecyclerView.setAdapter(mAdapter);
return mView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayList<DatabaseModel> LineList = new ArrayList<>();
LineList.clear();
mAdapter = new DataAdapter(LineList);
DatabaseHelper db = new DatabaseHelper(getContext());
final List<DatabaseModel> m = db.getAllUsers();
if (m.size() > 0) {
for (int i = 0; i < m.size(); i++) {
LineList.add(m.get(i));
mAdapter.notifyDataSetChanged();
}
}
db.close();
}
}
and this is my DataHelper code:
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "MetroDB";//name of the
database
private static final String TABLE_NAME = "stationtime";//name for the
table
static String db_path = "/data/data/ir.shirazmetro/databases/";
private static final String Station = "station";
private static final String Time = "time";
private static final String Line = "line";
private final Context context;
private SQLiteDatabase database;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE IF NOT EXISTS " +
TABLE_NAME + "(" + Station + " TEXT," + Time + " TEXT," + Line + " TEXT)";
db.execSQL(CREATE_CONTACTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
private boolean checkExist() {
SQLiteDatabase db = null;
try {
db = SQLiteDatabase.openDatabase(db_path + DATABASE_NAME, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLException e) {
}
return db != null;
}
private void copyDatabase() throws IOException {
OutputStream myOutput = new FileOutputStream(db_path +
DATABASE_NAME);
byte[] buffer = new byte[1024];
int length;
InputStream myInput = context.getAssets().open(DATABASE_NAME +
".db");
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myInput.close();
myOutput.flush();
myOutput.close();
}
public void importIfNotExist() throws IOException {
boolean dbExist = checkExist();
if (!dbExist) {
this.getReadableDatabase();
try {
copyDatabase();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void open() {
database = SQLiteDatabase.openDatabase(db_path + DATABASE_NAME, null,
SQLiteDatabase.OPEN_READWRITE);
}
public List<DatabaseModel> getAllUsers() {
List<DatabaseModel> contactList = new ArrayList<DatabaseModel>();
String whatStation = C.whatStation;
String whatLine = C.whatLine;
String selectQuery = "SELECT " + Time + " FROM " + TABLE_NAME + "
WHERE " + Station + " LIKE '%" + whatStation + "%' AND " + Line + " LIKE '%"
+ whatLine + "%'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.moveToFirst();
if (cursor.getCount() > 0) {
do {
DatabaseModel m = new DatabaseModel();
m.setTime(cursor.getString(cursor.getColumnIndex(Time)));
contactList.add(m);
} while (cursor.moveToNext());
}
return contactList;
}
}
and finally this is my activity code:
public class station extends BaseActivity {
Toolbar mToolbar;
private TabLayout tbLayout;
private ViewPager vPager;
RecyclerView.Adapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_station);
final DatabaseHelper helper = new DatabaseHelper(this);
try {
helper.importIfNotExist();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
mToolbar = findViewById(R.id.tlbr1);
setSupportActionBar(mToolbar);
initView();
setupWithViewPager();
tbLayout.addOnTabSelectedListener(new
TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}
public void line1(View view) {
Intent line1 = new Intent(this, line1.class);
startActivity(line1);
}
private void setupWithViewPager() {
BasePagerAdapter basePagerAdapter = new BasePagerAdapter(this,
getSupportFragmentManager());
vPager.setAdapter(basePagerAdapter);
tbLayout.setupWithViewPager(vPager);
}
private void initView() {
vPager = findViewById(R.id.view_pager);
tbLayout = findViewById(R.id.tab_layout);
backBtn = findViewById(R.id.backBtn);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.backBtn:
line1(view);
return;
}
}
}

how can i change the contents of recycleview at the same time change the data in sqlite?

I have a button in recycleview(part of cardview, which is generated for each insertion) which increments an specific column with id in SQLite, the data gets changed but I have to relaunch the activity for it to change.
The changed data has to be shown in textview.
I am new to this, how can I make them change dynamically?
public class attendence_recycleadapter extends RecyclerView.Adapter<attendence_recycleadapter.ViewHolder> {
private List<attendence> mattendence_list;
private Context mcontext;
public RecyclerView mrecycleview;
#NonNull
#Override
public attendence_recycleadapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater= LayoutInflater.from(parent.getContext());
View v=inflater.inflate(R.layout.attendence_recycleview_card,parent,false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull attendence_recycleadapter.ViewHolder holder, final int position) {
final attendence attendence= mattendence_list.get(position);
holder.subname.setText("NAME: " + attendence.getSubname());
holder.subcredit.setText("CREDIT: " + attendence.getCredit());
holder.bunks.setText("BUNKS: " + attendence.getBunks());
holder.deletesub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Myhelper myhelper = new Myhelper(mcontext);
myhelper.delete(attendence.getId(),mcontext);
notifyItemRemoved(position);
notifyItemRangeChanged(position,mattendence_list.size());
notifyDataSetChanged();
delete(position);
}
});
holder.addbunk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Myhelper myhelper = new Myhelper(mcontext);
myhelper.updatebunk(attendence.getId());
Toast.makeText(mcontext,"+1 class bunked",Toast.LENGTH_SHORT).show();
}
});
holder.deletebunk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Myhelper myhelper=new Myhelper(mcontext);
myhelper.updatebunkdelete(attendence.getId());
Toast.makeText(mcontext,"Bunk deleted",Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return mattendence_list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView subname;
public TextView subcredit;
public TextView bunks;
public View layout;
public TextView addbunk;
public TextView deletebunk;
public TextView deletesub;
public ViewHolder(View itemView) {
super(itemView);
layout=itemView;
subname=(TextView)itemView.findViewById(R.id.attendernce_subname);
subcredit=(TextView)itemView.findViewById(R.id.attendernce_credit);
bunks=(TextView)itemView.findViewById(R.id.attendernce_bunks);
deletebunk =(TextView)itemView.findViewById(R.id.attendence_deletebunk);
addbunk = (TextView) itemView.findViewById(R.id.attendence_addbunk);
deletesub = (TextView) itemView.findViewById(R.id.attendence_deletesub);
}
}
public void add(int position,attendence attendence2){
mattendence_list.add(position,attendence2);
notifyItemInserted(position);
}
public void delete(int position){
mattendence_list.remove(position);
notifyItemRemoved(position);
}
public attendence_recycleadapter(List<attendence> mydataset, Context context, RecyclerView recyclerView){
mattendence_list = mydataset;
mcontext = context;
mrecycleview= recyclerView;
}
}
myactivity:
public class Manage_attendence extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private attendence_recycleadapter attendence_recycleadapter;
String filter="";
TextView add_subject;
Dialog mycustomDialog;
Myhelper myhelper;
SQLiteDatabase sqLiteDatabase;
Spinner nema_of_credit;
EditText name_of_subject;
String spinner_string = new String();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manage_attendence);
add_subject=(TextView)findViewById(R.id.add_subject_dialog);
mycustomDialog = new Dialog(this);
myhelper = new Myhelper(this);
sqLiteDatabase = myhelper.getWritableDatabase();
add_subject.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setupDialog();
}
});
recyclerView= (RecyclerView)findViewById(R.id.attendence_recycleview);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
attendence_recycleadapter= new attendence_recycleadapter(myhelper.list(filter),this,recyclerView);
recyclerView.setAdapter(attendence_recycleadapter);
name_of_subject = (EditText) mycustomDialog.findViewById(R.id.name_of_subject);
nema_of_credit = (Spinner) mycustomDialog.findViewById(R.id.subject_credit);
}
public void setupDialog() {
mycustomDialog.setContentView(R.layout.dialog_add_subject);
TextView close = (TextView) mycustomDialog.findViewById(R.id.subject_delete);
close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mycustomDialog.dismiss();
}
});
exqButton();
mycustomDialog.setCancelable(false);
mycustomDialog.show();
mycustomDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
}
private void exqButton() {
TextView add =(TextView)mycustomDialog.findViewById(R.id.add);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name_of_subject = (EditText) mycustomDialog.findViewById(R.id.name_of_subject);
nema_of_credit = (Spinner) mycustomDialog.findViewById(R.id.subject_credit);
String xValues=String.valueOf(name_of_subject.getText());
spinner_string=nema_of_credit.getSelectedItem().toString();
String yValues= ((String.valueOf(spinner_string)));
boolean insertData = myhelper.insertData(xValues,yValues,0);
if (insertData==true){
Toast.makeText(Manage_attendence.this,"data inserted sucessfully",Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(Manage_attendence.this,"data inserted failed",Toast.LENGTH_SHORT).show();
}
name_of_subject.setText("");
mycustomDialog.dismiss();
}
});
}
}
mysqlitehelper:
public class Myhelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME="mydatabase.db";
public static final String TABLE_NAME="mytable";
public static final String COLUMN_ID="_id";
public static final String COL_1="NAME";
public static final String COL_2="CREDIT";
public static final String COL_3="BUNKS";
public static final String[] COLUMNS ={COLUMN_ID,COL_1,COL_2,COL_3};
Context con;
public Myhelper(Context context) {
super(context, DATABASE_NAME, null, 1);
con = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable= "CREATE TABLE " + TABLE_NAME + " (" + COLUMN_ID +" INTEGER PRIMARY KEY AUTOINCREMENT, " + " NAME TEXT, CREDIT TEXT, BUNKS INTEGER )";
db.execSQL(createTable);
Toast.makeText(con,"table created",Toast.LENGTH_SHORT).show();
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+ TABLE_NAME);
onCreate(db);
}
public boolean insertData(String x,String y,int z){
SQLiteDatabase db=this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1, String.valueOf(x));
contentValues.put(COL_2,String.valueOf(y));
contentValues.put(COL_3,z);
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1) {
return false;
} else {
return true;
}
}
public ArrayList<String> queryXdata(){
ArrayList<String> xnewdata= new ArrayList<String>();
String query = "SELECT "+ COL_1 + " FROM " + TABLE_NAME;
SQLiteDatabase db=this.getWritableDatabase();
Cursor cursor= db.rawQuery(query,null);
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
xnewdata.add(cursor.getString(cursor.getColumnIndex(COL_1)));
}
cursor.close();
return xnewdata;
}
public ArrayList<Integer> queryYdata(){
ArrayList<Integer> ynewdata= new ArrayList<Integer>();
String query = "SELECT "+ COL_3+ " FROM " + TABLE_NAME;
SQLiteDatabase db=this.getWritableDatabase();
Cursor cursor= db.rawQuery(query,null);
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
ynewdata.add(cursor.getInt(cursor.getColumnIndex(COL_3)));
}
cursor.close();
return ynewdata;
}
public ArrayList<Integer> queryZdata(){
ArrayList<Integer> znewdata= new ArrayList<Integer>();
String query = "SELECT "+ COL_2+ " FROM " + TABLE_NAME;
SQLiteDatabase db=this.getWritableDatabase();
Cursor cursor= db.rawQuery(query,null);
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
znewdata.add(((cursor.getColumnIndex(COL_2))));
}
cursor.close();
return znewdata;
}
public attendence getdetails(long id){
SQLiteDatabase db = this.getWritableDatabase();
String query= "SELECT" + COL_2+" FROM " + TABLE_NAME +" WHERE _id=" + id;
Cursor cursor= db.rawQuery(query,null);
attendence attendence1= new attendence();
if (cursor.getCount()>0){
cursor.moveToFirst();
attendence1.setSubname(cursor.getString(cursor.getColumnIndex(COL_1)));
attendence1.setCredit(cursor.getString(cursor.getColumnIndex(COL_2)));
attendence1.setBunks(cursor.getInt(cursor.getColumnIndex(COL_3)));
}
return attendence1;
}
public void delete(long id,Context context){
SQLiteDatabase db=this.getWritableDatabase();
db.execSQL("DELETE FROM "+TABLE_NAME+" WHERE _id='"+id+"'");
Toast.makeText(context,"delted",Toast.LENGTH_SHORT).show();
}
public List<attendence> list(String filter){
String query;
if (filter.equals("")){
query = "SELECT * FROM " + TABLE_NAME ;
}
else {
query= " SELECT * FROM " + TABLE_NAME ;
}
List<attendence> linkedlist = new LinkedList<>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query,null);
attendence attendence;
if (cursor.moveToFirst()){
do {
attendence = new attendence();
attendence.setId(cursor.getLong(cursor.getColumnIndex(COLUMN_ID)));
attendence.setSubname(cursor.getString(cursor.getColumnIndex(COL_1)));
attendence.setCredit(cursor.getString(cursor.getColumnIndex(COL_2)));
attendence.setBunks(cursor.getInt(cursor.getColumnIndex(COL_3)));
linkedlist.add(attendence);
}
while (cursor.moveToNext());
}
return linkedlist;
}
public int getbunk(long id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME + " WHERE " + COLUMN_ID + " = " + String.valueOf(id), null);
int output = -1;
if (cursor != null) {
if (cursor.moveToFirst()) {
output = cursor.getInt(cursor.getColumnIndex(COL_3));
}
cursor.close();
}
return output;
}
public void updatebunk(long id){
SQLiteDatabase db = this.getWritableDatabase();
int bunk = getbunk(id);
int bunkinc= ++bunk;
ContentValues contentValues= new ContentValues();
contentValues.put(COL_3,bunkinc);
db.update(TABLE_NAME,contentValues,COLUMN_ID+ "=?",new String[]{String.valueOf(id)});
db.close();
}
public void updatebunkdelete(long id){
SQLiteDatabase db = this.getWritableDatabase();
int bunk = getbunk(id);
int bunkinc= --bunk;
ContentValues contentValues= new ContentValues();
contentValues.put(COL_3,bunkinc);
db.update(TABLE_NAME,contentValues,COLUMN_ID+ "=?",new String[]{String.valueOf(id)});
db.close();
}
}
Change the updatebunk method:
public int updatebunk(long id){
SQLiteDatabase db = this.getWritableDatabase();
int bunk = getbunk(id);
int bunkinc= ++bunk;
ContentValues contentValues= new ContentValues();
contentValues.put(COL_3, bunkinc);
db.update(TABLE_NAME,contentValues,COLUMN_ID+ "=?",new String[]{String.valueOf(id)});
db.close();
return bunkinc;
}
then in your adapter change the listener of addbunk
holder.addbunk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Myhelper myhelper = new Myhelper(mcontext);
int newbunk = myhelper.updatebunk(attendence.getId());
attendence.setBunks(newbunk);
mattendence_list.set(position, attendence);
notifyDataSetChanged();
Toast.makeText(mcontext,"+1 class bunked",Toast.LENGTH_SHORT).show();
}
});

How to refresh adapter and deselect all items each time when user clicks on multispinner?

I want to refresh the getview() of baseadapter each time when user click on multispinner. Also wants to deselect all the selected checkbox.
Anybody please help.
Blockquote
Below is my multispinner java class
public class MultiSpinnerSearch extends Spinner implements OnCancelListener {
private static final String TAG = MultiSpinnerSearch.class.getSimpleName();
private List<KeyPairBoolData> items;
private String defaultText = "";
private String spinnerTitle = "";
private SpinnerListener listener;
private int limit = 0;
private int selected = 0;
private LimitExceedListener limitListener;
MyAdapter adapter;
public static AlertDialog.Builder builder;
public static AlertDialog ad;
public MultiSpinnerSearch(Context context) {
super(context);
}
public MultiSpinnerSearch(Context arg0, AttributeSet arg1) {
super(arg0, arg1);
TypedArray a = arg0.obtainStyledAttributes(arg1, R.styleable.MultiSpinnerSearch);
limit = a.getIndexCount();
for (int i = 0; i < limit; ++i) {
int attr = a.getIndex(i);
if (attr == R.styleable.MultiSpinnerSearch_hintText) {
spinnerTitle = a.getString(attr);
defaultText = spinnerTitle;
break;
}
}
Log.i(TAG, "spinnerTitle: " + spinnerTitle);
a.recycle();
}
public MultiSpinnerSearch(Context arg0, AttributeSet arg1, int arg2) {
super(arg0, arg1, arg2);
}
public void setLimit(int limit, LimitExceedListener listener) {
this.limit = limit;
this.limitListener = listener;
}
public List<KeyPairBoolData> getSelectedItems() {
List<KeyPairBoolData> selectedItems = new ArrayList<>();
for (KeyPairBoolData item : items) {
if (item.isSelected()) {
selectedItems.add(item);
}
}
return selectedItems;
}
public List<Long> getSelectedIds() {
List<Long> selectedItemsIds = new ArrayList<>();
for (KeyPairBoolData item : items) {
if (item.isSelected()) {
selectedItemsIds.add(item.getId());
}
}
return selectedItemsIds;
}
#Override
public void onCancel(DialogInterface dialog) {
// refresh text on spinner
StringBuilder spinnerBuffer = new StringBuilder();
for (int i = 0; i < items.size(); i++) {
if (items.get(i).isSelected()) {
spinnerBuffer.append(items.get(i).getName());
spinnerBuffer.append(", ");
}
}
String spinnerText = spinnerBuffer.toString();
if (spinnerText.length() > 2)
spinnerText = defaultText;
else
spinnerText = defaultText;
ArrayAdapter<String> adapterSpinner = new ArrayAdapter<>(getContext(), R.layout.textview_for_spinner, new String[]{spinnerText});
setAdapter(adapterSpinner);
if (adapter != null)
adapter.notifyDataSetChanged();
listener.onItemsSelected(items);
}
#Override
public boolean performClick() {
builder = new AlertDialog.Builder(new ContextThemeWrapper(getContext(), R.style.Material_App_Dialog));
builder.setTitle(spinnerTitle);
final LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View view = inflater.inflate(R.layout.alert_dialog_listview_search, null);
builder.setView(view);
final ListView listView = (ListView) view.findViewById(R.id.alertSearchListView);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setFastScrollEnabled(false);
adapter = new MyAdapter(getContext(), items);
listView.setAdapter(adapter);
final TextView emptyText = (TextView) view.findViewById(R.id.empty);
listView.setEmptyView(emptyText);
final EditText editText = (EditText) view.findViewById(R.id.alertSearchEditText);
editText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
adapter.getFilter().filter(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
builder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Log.i(TAG, " ITEMS : " + items.size());
dialog.cancel();
}
});
builder.setOnCancelListener(this);
ad = builder.show();
return true;
}
public void setItems(List<KeyPairBoolData> items, int position, SpinnerListener listener) {
this.items = items;
this.listener = listener;
StringBuilder spinnerBuffer = new StringBuilder();
for (int i = 0; i < items.size(); i++) {
if (items.get(i).isSelected()) {
spinnerBuffer.append(items.get(i).getName());
spinnerBuffer.append(", ");
}
}
if (spinnerBuffer.length() > 2)
defaultText = spinnerBuffer.toString().substring(0, spinnerBuffer.toString().length() - 2);
ArrayAdapter<String> adapterSpinner = new ArrayAdapter<>(getContext(), R.layout.textview_for_spinner, new String[]{defaultText});
setAdapter(adapterSpinner);
if (position != -1) {
items.get(position).setSelected(true);
//listener.onItemsSelected(items);
onCancel(null);
}
}
public interface LimitExceedListener {
void onLimitListener(KeyPairBoolData data);
}
//Adapter Class
public class MyAdapter extends BaseAdapter implements Filterable {
List<KeyPairBoolData> arrayList;
List<KeyPairBoolData> mOriginalValues; // Original Values
LayoutInflater inflater;
public MyAdapter(Context context, List<KeyPairBoolData> arrayList) {
this.arrayList = arrayList;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder {
TextView textView;
CheckBox checkBox;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
Log.i(TAG, "getView() enter");
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.item_listview_multiple, parent, false);
holder.textView = (TextView) convertView.findViewById(R.id.alertTextView);
holder.checkBox = (CheckBox) convertView.findViewById(R.id.alertCheckbox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final int backgroundColor = (position % 2 == 0) ? R.color.list_background : R.color.list_background;
convertView.setBackgroundColor(ContextCompat.getColor(getContext(), backgroundColor));
if (position==0)
{
holder.textView.setTextColor(Color.BLACK);
}
if (position==3)
{
holder.textView.setTextColor(Color.GREEN);
convertView.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.list_selected));
}
final KeyPairBoolData data = arrayList.get(position);
holder.textView.setText(data.getName());
holder.textView.setTypeface(null, Typeface.NORMAL);
holder.checkBox.setChecked(data.isSelected());
convertView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (data.isSelected()) { // unselect
selected--;
} else if (selected == limit) { // select with limit
if (limitListener != null)
limitListener.onLimitListener(data);
return;
} else { // selected
selected++;
}
final ViewHolder temp = (ViewHolder) v.getTag();
temp.checkBox.setChecked(!temp.checkBox.isChecked());
data.setSelected(!data.isSelected());
Log.i(TAG, "On Click Selected Item : " + data.getName() + " : " + data.isSelected());
}
});
holder.checkBox.setTag(holder);
return convertView;
}
#SuppressLint("DefaultLocale")
#Override
public Filter getFilter() {
return new Filter() {
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
arrayList = (List<KeyPairBoolData>) results.values; // has the filtered values
notifyDataSetChanged(); // notifies the data with new filtered values
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults(); // Holds the results of a filtering operation in values
List<KeyPairBoolData> FilteredArrList = new ArrayList<>();
if (mOriginalValues == null) {
mOriginalValues = new ArrayList<>(arrayList); // saves the original data in mOriginalValues
}
/********
*
* If constraint(CharSequence that is received) is null returns the mOriginalValues(Original) values
* else does the Filtering and returns FilteredArrList(Filtered)
*
********/
if (constraint == null || constraint.length() == 0) {
// set the Original result to return
results.count = mOriginalValues.size();
results.values = mOriginalValues;
} else {
constraint = constraint.toString().toLowerCase();
for (int i = 0; i < mOriginalValues.size(); i++) {
Log.i(TAG, "Filter : " + mOriginalValues.get(i).getName() + " -> " + mOriginalValues.get(i).isSelected());
String data = mOriginalValues.get(i).getName();
if (data.toLowerCase().contains(constraint.toString())) {
FilteredArrList.add(mOriginalValues.get(i));
}
}
// set the Filtered result to return
results.count = FilteredArrList.size();
results.values = FilteredArrList;
}
return results;
}
};
}
}
}
And from my main activity
MultiSpinnerSearch searchSpinner = (MultiSpinnerSearch) findViewById(R.id.searchMultiSpinner);
searchSpinner.setItems(listArray, -1, new SpinnerListener() {
#Override
public void onItemsSelected(List<KeyPairBoolData> items) {
for (int i = 0; i < items.size(); i++) {
if (items.get(i).isSelected()) {
Log.i("TAG", i + " : " + items.get(i).getName() + " : " + items.get(i).isSelected());
FlashMessage(i + " : " + items.get(i).getName() + " : " + items.get(i).isSelected());
if (GroupName.equals(""))
{
GroupName=GroupName+items.get(i).getName();
Group_stuid=Group_stuid+student_idlist[i+1];
}
else
{
GroupName=GroupName+","+items.get(i).getName();
Group_stuid=Group_stuid+"#"+student_idlist[i+1];
}
}
}
FlashMessage("grp name : "+GroupName);
FlashMessage("grp id : "+Group_stuid);
Audiofilename=appfunct.checkfile(eventType,acdses_sct,class_sct,category_sct,subject_sct,test_sct,Group_stuid,GroupName);
outfolder=appfunct.outfldr();
Group_stuid=Group_stuid.replaceAll("/","-");
File create_stuid=new File(outfolder.toString()+"/"+Group_stuid);
if(!create_stuid.exists()) {
create_stuid.mkdirs();
}
FlashMessage(""+GroupFoldername);
Group_listFiles=appfunct.showlistfiles(GroupFoldername);
if (Group_listFiles != null)
{
final CustomGroupFolder_ListDispaly adapter1 = new CustomGroupFolder_ListDispaly(Group_recording.this,R.layout.group_item_listview,Group_listFiles);
group_listview.setAdapter(adapter1);
}
GroupName="";
Group_stuid="";
selected_students=appfunct.getSelectedNamesGroup(GroupFoldername);
}
});
FlashMessage("out : grp id "+Group_stuid);
searchSpinner.setLimit(2, new MultiSpinnerSearch.LimitExceedListener() {
#Override
public void onLimitListener(KeyPairBoolData data) {
Toast.makeText(getApplicationContext(),
"Limit exceed ", Toast.LENGTH_LONG).show();
}
});
apply this to your adapter adapter.notifyDataSetChanged();

ExpandableListView extended using BaseExpandableListAdapter but reading from Sqlite DB example

Senior Geeks.
I'd like to request a simple but fully working example of how to implement an ExpandableListView while extending from BaseExpandableListAdapter Yet Reading data from an Sqlite Database.
I have researched and experimented on the question (see here), but with minimal success where i was able to display some data in the header, albeit it was same values repeating for all group headers. Also child items don't show.
The reason for extending with BaseExpandableListAdapter is to have a custom layout for the group header. The reason for SQLite access is naturally because thats where my data is stored.
All examples trawled on the net so far use either SimpleCursorTreeAdapter or CursorTreeAdapter as the extender in DB based applications or simply BaseExpandableListAdapter when data used is in ArrayLists.
Below is the Experimentation thus far. (with this code,only the group header is populated with the same figures over and over. Childitems dont appear)
public class ExpandableListViewAdapterCustom extends BaseExpandableListAdapter {
protected Activity currentActivity;
public ExpandableListViewAdapterCustom(Activity callingActivity){
this.currentActivity = callingActivity;
}
private Cursor mGroupsCursorLocal ;
private Cursor mChildCursor;
private Context ctx;
private int groupItem;
private int childItem;
private String[] fieldsToUseFromGroupCursor;
private int[] screenTextsToMapGroupDataTo;
private String[] fieldsToUseFromChildCursor;
private int[] screenTextsToMapChildDataTo;
public ArrayList<String> tempChild;
public LayoutInflater minflater;
public Activity activity;
public int intGroupTotal;
public void setCurrentActivity(Activity activity) {
this.activity = activity;
}
public void setCtx(Context ctx) {
this.ctx = ctx;
}
public void setGroupItem(int groupItem) {
this.groupItem = groupItem;
}
public void setChildItem(int childItem) {
this.childItem = childItem;
}
public Activity getCurrentActivity() {
return currentActivity;
}
public Cursor getmGroupsCursorLocal() {
return mGroupsCursorLocal;
}
public Context getCtx() {
return currentActivity.getBaseContext();
}
public void setmGroupsCursorLocal(Cursor mGroupsCursor) {
this.mGroupsCursorLocal = mGroupsCursor;
}
public ExpandableListViewAdapterCustom(Cursor mGroupsCursor,
Activity activity,
int groupItem,
int childItem,
String[] fieldsToUseFromGroupCursor,
int[] screenTextsToMapGroupDataTo,
String[] fieldsToUseFromChildCursor,
int[] screenTextsToMapChildDataTo) {
DatabaseRoutines db = new DatabaseRoutines(activity);
setmGroupsCursorLocal(mGroupsCursor);
mGroupsCursorLocal = db.fetchGroup();
activity.startManagingCursor (mGroupsCursor);
mGroupsCursorLocal.moveToFirst();
mChildCursor=db.fetchChildren(mGroupsCursorLocal.getColumnIndex("Year"));
mChildCursor.moveToFirst();
activity.startManagingCursor(mChildCursor);
setCtx(activity);
setCurrentActivity(activity);
}
public void setInflater(LayoutInflater mInflater, Activity act) {
this.minflater = mInflater;
activity = act;
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return null;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return 0;
}
#Override
public View getChildView(int groupPosition,
int childPosition,boolean
isLastChild,
View convertView,
ViewGroup parent) {
View v = convertView;
if (v == null)
{
LayoutInflater inflater =
(LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.exp_listview_childrow, parent, false);
}
TextView txtMonth = (TextView) v.findViewById(R.id.txtMonth);
TextView txtMonthAmountSent = (TextView)
v.findViewById(R.id.txtMonthAmountSentValue);
TextView txtMonthReceived = (TextView)
v.findViewById(R.id.txtMonthAmountReceivedValue);
txtMonth.setText(mChildCursor.getString(mChildCursor.getColumnIndex("Month")));
txtMonthAmountSent.setText
(mChildCursor.getString(mChildCursor.getColumnIndex("TotalSent")));
txtMonthReceived.setText
(mChildCursor.getString(mChildCursor.getColumnIndex("TotalReceived")));
return v;
}
#Override
public int getChildrenCount(int groupPosition) {
return (mChildCursor.getCount());
}
#Override
public Object getGroup(int groupPosition) {
return null;
}
#Override
public int getGroupCount() {
return mGroupsCursorLocal.getCount();
}
#Override
public void onGroupCollapsed(int groupPosition) {
super.onGroupCollapsed(groupPosition);
}
#Override
public void onGroupExpanded(int groupPosition) {
super.onGroupExpanded(groupPosition);
}
#Override
public long getGroupId(int groupPosition) {
return 0;
}
#Override
public View getGroupView(
int groupPosition,
boolean isExpanded,
View convertView,
ViewGroup parent)
{
View v = convertView;
if (v == null) {
LayoutInflater inflater =
(LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.exp_listview_groupheader, parent, false);
}
TextView txtYear = (TextView) v.findViewById(R.id.txtYearValue);
TextView txtAmountSent = (TextView) v.findViewById(R.id.txtAmountSentValue);
TextView txtAmountRecieved = (TextView)
v.findViewById(R.id.txtAmountReceivedValue);
txtYear.setText(mGroupsCursorLocal.getString(
mGroupsCursorLocal.getColumnIndex("Year")));
txtAmountSent.setText(
mGroupsCursorLocal.getString(mGroupsCursorLocal.getColumnIndex("TotalSent")));
txtAmountRecieved.setText(
GroupsCursorLocal.getString(mGroupsCursorLocal.getColumnIndex("TotalReceived")));
return v;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return false;
}
}
The Database code is like this
public Cursor fetchGroup() {
SQLiteDatabase db = this.getReadableDatabase(); //if memory leaks check here
String query = "SELECT DISTINCT MIN(ID) AS id,
Year, SUM(SentAmount) AS TotalSent, SUM(ReceivedAmount) AS TotalReceived
FROM MyTbl GROUP BY Year ORDER BY Year DESC ";
return db.rawQuery(query, null);}
public Cursor fetchChildren(int Yr) {
SQLiteDatabase db = this.getReadableDatabase(); //if memory leaks check here
String query = "SELECT MIN(ID) AS id,
Year, Month, SUM(SentAmount) AS TotalSent,
SUM(ReceivedAmount) AS TotalReceived
FROM MyTbl Where Year= "+ Yr +" GROUP BY Year,
Month ORDER BY Year DESC, Month DESC";
return db.rawQuery(query, null);
}
The Code is called from main activity using the following
ExpandableListView elv = (ExpandableListView)
findViewById(R.id.expandableListView);
ExpandableListAdapter mAdapter = new
ExpandableListViewAdapterCustom(mGroupsCursor,
MyActivity.this,
R.layout.exp_listview_groupheader,// Your row layout for a group
R.layout.exp_listview_childrow, // Your row layout for a child
new String[] { "Year",
"TotalSent",
"TotalReceived" },// Field(s) to use from group cursor
new int[] {R.id.txtYearValue,
R.id.txtAmountSentValue,
R.id.txtAmountReceivedValue },// Widget ids to put group data
into new String[] { "Year","Month",
"TotalSent",
"TotalReceived" }, // Field(s) to use from child cursors new
int[] {R.id.txtMonthValue,
R.id.txtMonthAmountSentValue,
R.id.txtMonthAmountReceivedValue});// Widget ids to put child d
data into
elv.setClickable(true);
elv.setAdapter(mAdapter); // set the
After almost two weeks and no answer, i decided to simply use an ExpandableListView example using ArrayLists and modified it such that the ArrayLists were populated by data from the DB. Its not what i wanted but it works. I was actually suprised that nowhwere on the web is there an example of using ExpandableListview extended form BaseAdapter but reading from SQlite using say cursorTreeAdapter or SimpleCursorAdapter.
Below is how i did it in case it helps someone in future. the code shown is the bit that populates the ArrayList from DB
public ArrayList<ExpandListGroup> SetStandardGroups() {
ArrayList<ExpandListGroup> list = new ArrayList<ExpandListGroup>();
ArrayList<ExpandListChild> list2 = new ArrayList<ExpandListChild>();
int intMonthNum;
ExpandListGroup grp;
ExpandListChild chld;
//initialize db code here
DatabaseRoutines db = new DatabaseRoutines(this);
//create the Groups retreival cursor;
Cursor mGroupsCursor = db.fetchGroup();
//---the database call is done using this code which is in my
//---custom db class which implements the sqlhelper methods etc
//------start of db code snippet-------------------------------
//---public Cursor fetchGroup() {
//---SQLiteDatabase db = this.getReadableDatabase();
//--- String query = "SELECT DISTINCT MIN(ID) AS id, Year,
//--- SUM(SentAmount) AS TotalSent,
//--- SUM(ReceivedAmount) AS TotalReceived
//--- FROM Tbl GROUP BY Year ORDER BY Year DESC ";
//--- return db.rawQuery(query, null);}
//------end of db code snippet-------------------------------
mGroupsCursor.moveToFirst();
//method is depreciated from api14 but i'm targeting Gingerbread (api10) so i need to use it.
startManagingCursor(mGroupsCursor);
int intYear;
int intHeaderCounter = 0;
int intChildCounter = 0;
int intChildTotalCount = 0;
int intHeaderTotalGroupCount = mGroupsCursor.getCount();
//set the starting Year for the loop, if there is data;
if (intHeaderTotalGroupCount > 0) {
//get the first year
//intYear = mGroupsCursor.getInt(mGroupsCursor.getColumnIndex("Year"));
for (intHeaderCounter = 0; intHeaderCounter < intHeaderTotalGroupCount; intHeaderCounter++) {
grp = new ExpandListGroup();
intYear = mGroupsCursor.getInt(mGroupsCursor.getColumnIndex("Year"));
grp.setYear(intYear);
grp.setYearAmountReceived(mGroupsCursor.getDouble(mGroupsCursor.getColumnIndex("TotalReceived")));
grp.setYearAmountSent(mGroupsCursor.getDouble(mGroupsCursor.getColumnIndex("TotalSent")));
grp.setTag(mGroupsCursor.getString(mGroupsCursor.getColumnIndex("id")));
//Prepare counters for inner loop for child items of each
Cursor mChildCursor = db.fetchChildren(intYear);
mChildCursor.moveToFirst();
intChildTotalCount = mChildCursor.getCount();
//populate child items
for (intChildCounter = 0; intChildCounter < intChildTotalCount; intChildCounter++) {
chld = new ExpandListChild();
intMonthNum = mChildCursor.getInt(mChildCursor.getColumnIndex("Month"));
chld.setMonthNumber(intMonthNum);
chld.setTotalReceivedMonth(mChildCursor.getInt(mChildCursor.getColumnIndex("TotalReceived")));
chld.setTotalSentMonth(mChildCursor.getInt(mChildCursor.getColumnIndex("TotalSent")));
chld.setTag(mGroupsCursor.getString(mGroupsCursor.getColumnIndex("id")).toString());
list2.add(chld);
//grp.setItems(list2);
//move to next child record;
mChildCursor.moveToNext();
}
grp.setItems(list2);
list.add(grp);
list2 = new ArrayList<ExpandListChild>();
//move to next parent record;
mGroupsCursor.moveToNext();
}
} else {
log.d( "yourdebugtag_here", "Sorry, No Transactions Found.");
}
//db.close();
return list;
}

Resources