How to start a new activity from the current in expandableListView's setOnChildCliclkListener? - expandablelistview

expListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
String headername = (String) parent.getExpandableListAdapter().getGroup(groupPosition);
String childname = (String) parent.getExpandableListAdapter().getChild(groupPosition,childPosition);
Log.d("Parent name",headername);
Log.d("Child name", childname);
Intent intent = new Intent(ViewActivity.this,ShowActivity.class);
intent.putExtra("Parent",headername);
intent.putExtra("Child",childname);
intent.putExtra("Path",myPath);
startActivity(intent);
return true;
}
});

Just use ActivityName.this.startActivity() and that would call the required intent.

Related

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

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);
}

I want add multiple Data Items of same date in single Card View in Android

I want data to be displayed as shown in imageenter image description here
I want to add multiple item of same date in single card view instead of creating another card view for the item of same date
I have tried in Android Studio grouping recycler view called as sanctioned Recycler view where I used date as header but it's not the solution
My Adapter Class
private Context mContext;
List<ListItem> consolidatedList = new ArrayList<>();
public AttendanceAdapter(Context context, List<ListItem>
consolidatedList) {
this.consolidatedList = consolidatedList;
this.mContext = context;
}
#Override
public RecyclerView.ViewHolder
onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder viewHolder = null;
LayoutInflater inflater =
LayoutInflater.from(parent.getContext());
switch (viewType) {
case ListItem.TYPE_GENERAL:
View v1 =
inflater.inflate(R.layout.attendance_adapter_layout, parent,
false);
viewHolder = new GeneralViewHolder(v1);
break;
case ListItem.TYPE_DATE:
View v2 =
inflater.inflate(R.layout.attn_item_header, parent, false);
viewHolder = new DateViewHolder(v2);
break;
}
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder
viewHolder, int position)
{
switch (viewHolder.getItemViewType()) {
case ListItem.TYPE_GENERAL:
GeneralItem generalItem = (GeneralItem)
consolidatedList.get(position);
GeneralViewHolder generalViewHolder=
(GeneralViewHolder) viewHolder;
//generalViewHolder.txt_date.setText(
generalItem.getAttendance_data().getDate());
generalViewHolder.txt_month.setText(
generalItem.getAttendance_data().getMonth_name());
generalViewHolder.txt_date.setText(
generalItem.getAttendance_data().getDate_no());
generalViewHolder.txt_out.setText(
generalItem.getAttendance_data().getAttn_out_time());
generalViewHolder.txt_in.setText(
generalItem.getAttendance_data().getAttn_In_time());
generalViewHolder.txtreason.setText
(generalItem.getAttendance_data().getRemark());
break;
case ListItem.TYPE_DATE:
DateItem dateItem = (DateItem)
consolidatedList.get(position);
DateViewHolder dateViewHolder = (DateViewHolder) viewHolder;
dateViewHolder.txtTitle.setText(dateItem.getDate());
// Populate date item data here
break;
}
}
class DateViewHolder extends RecyclerView.ViewHolder {
protected TextView txtTitle;
public DateViewHolder(View v) {
super(v);
this.txtTitle = (TextView)
v.findViewById(R.id.attn_date);
}
}
// View holder for general row item
class GeneralViewHolder extends RecyclerView.ViewHolder {
protected TextView
txt_in,txtreason,txt_out,txt_date,txt_month;
public GeneralViewHolder(View v) {
super(v);
this.txt_in =v.findViewById(R.id.attn_in_txt);
this.txt_out=v.findViewById(R.id.attn_out_txt);
this.txtreason=v.findViewById(R.id.attn_reason_txt);
this.txt_date=v.findViewById(R.id.date_view);
this.txt_month=v.findViewById(R.id.month_view);
}
}
#Override
public int getItemViewType(int position) {
return consolidatedList.get(position).getType();
}
#Override
public int getItemCount() {
return consolidatedList != null ? consolidatedList.size() : 0;
}
}
MainActivity.Java
public class CurrentMonth extends AsyncTask<Void,Void,Void> {
#Override
protected Void doInBackground(Void... voids) {
attn_list_data_cur_month();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
updateUi();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
public void attn_list_data_cur_month(){
try {
this.connection=createConnection();
Statement stmt=connection.createStatement();
Calendar current_month_data = Calendar.getInstance();
current_month_data.add(Calendar.MONTH, 0);
//Calendar current_month_date = Calendar.getInstance();
//current_month_date.set(Calendar.DAY_OF_MONTH,0);
n=current_month_data.get(Calendar.DAY_OF_MONTH);
String current_month_year = new SimpleDateFormat("MMM-
yyyy").format(current_month_data.getTime());
String month_name=currentMonth.getText().toString();
for (int i=1;i<=n;i++) {
String date = i + "-" + current_month_year;
ResultSet resultSet = stmt.executeQuery("Select * from
MATTN_MAS where ATTN_DATE='" + date + "' and Username='" +
Username + "'");
String Attn_Type;
if (resultSet.next()) {
while (resultSet.next()) {
Attn_Type = resultSet.getString(8);
String Time = null;
String Reason = resultSet.getString(11);
if (Attn_Type.equals("I")) {
String Attn_Type_In = "I";
String Attn_Type_Out = null;
StringBuilder stringBuilder = new StringBuilder("" + i);
String date_no = stringBuilder.toString();
myOptions.add(new Attendance_Data(Attn_Type_In,
date, Reason, Attn_Type_Out, i, date_no, month_name));
} else {
String Attn_Type_Out = "O";
String Attn_Type_In = null;
StringBuilder stringBuilder = new StringBuilder("" + i);
String date_no = stringBuilder.toString();
myOptions.add(new Attendance_Data(Attn_Type_In,
date, Reason, Attn_Type_Out, i, date_no, month_name));
}
}
} else {
Attn_Type = "Absent";
String Time = null;
String Reason = null;
String out = null;
StringBuilder stringBuilder = new StringBuilder("" + i);
String date_no = stringBuilder.toString();
myOptions.add(new Attendance_Data(Attn_Type, date, Reason,
out, i, date_no, month_name));
}
}
}catch (Exception e){
System.out.println("my Error"+e);
}
}
public void updateUi(){
//sortedData= (List<PojoOfJsonArray>)
PojoOfJsonArray.sortList(myOptions);
HashMap<String, List<Attendance_Data>> groupedHashMap =
groupDataIntoHashMap(myOptions);
for (String date1 : groupedHashMap.keySet()) {
DateItem dateItem = new DateItem();
dateItem.setDate(date1);
consolidatedList.add(dateItem);
for (Attendance_Data pojoOfJsonArray : groupedHashMap.get(date1))
{
GeneralItem generalItem = new GeneralItem();
generalItem.setAttendance_data(pojoOfJsonArray);
consolidatedList.add(generalItem);
}
}
adapter = new AttendanceAdapter(this, consolidatedList);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
attn_report_view.setLayoutManager(layoutManager);
attn_report_view.setAdapter(adapter);
}
private HashMap<String, List<Attendance_Data>>
groupDataIntoHashMap(List<Attendance_Data> listOfPojosOfJsonArray) {
HashMap<String, List<Attendance_Data>> groupedHashMap = new HashMap<>
();
for (Attendance_Data pojoOfJsonArray : listOfPojosOfJsonArray) {
String hashMapKey = pojoOfJsonArray.getDate();
if (groupedHashMap.containsKey(hashMapKey)) {
// The key is already in the HashMap; add the pojo object
// against the existing key.
groupedHashMap.get(hashMapKey).add(pojoOfJsonArray);
} else {
List<Attendance_Data> list = new ArrayList<>();
list.add(pojoOfJsonArray);
groupedHashMap.put(hashMapKey, list);
}
}
return groupedHashMap;
}
I want to add multiple items of same date in same single single card view but instead it is creating multiple Card View for multiple items of same date
You have to use RecyclerView Multiple ViewTypes. for detail please check this example.
Also visit this example.
Yeah I found the solution it worked perfect for Me.....we
have to just make changes to the card View by removing
spaces..
.
like this below...
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardMaxElevation="0.1dp"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:background="#303030"
card_view:cardElevation="5dp"
android:foreground="?android:attr/selectableItemBackground"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_marginLeft="#dimen/dp_2"
android:layout_marginRight="#dimen/dp_2">
<...Your All Text Boxes and further Layout inside this
cardView...>
</android.support.v7.widget.CardView>
and I have add Header for each CardView....and it looks like
this
Outout is shown in below image

How to save the content of custom array class and adapter in list view save into text in android

I need your help I am new in android programming. How can I save all the content in the list view save into text file this is my code of try to save the file but the problem is how can i put the listview array list to get the data i don't know how to put it where to put it please help how to do it to save the content of my listview
Button code:
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
File myFile = new File("/sdcard/mysdfile.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
for (int i = 0; i < ChatBubbles.length; i++) {
myOutWriter.append(ChatBubbles[i] +"\n");
}
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Done writing SD 'mysdfile.txt'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
});
Chatbubble class:
package com.example.ezminute;
public class ChatBubble {
private String content;
private boolean myMessage;
public ChatBubble(String content, boolean myMessage) {
this.content = content;
this.myMessage = myMessage;
}
public String getContent() {
return content;
}
public boolean myMessage() {
return myMessage;
}
}
MessageAdapter:
package com.example.ezminute;
public class MessageAdapter extends ArrayAdapter<ChatBubble> {
private Activity activity;
private List<ChatBubble> messages;
public MessageAdapter(Activity context, int resource, List<ChatBubble> objects) {
super(context, resource, objects);
this.activity = context;
this.messages = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
int layoutResource = 0; // determined by view type
ChatBubble ChatBubble = getItem(position);
int viewType = getItemViewType(position);
if (ChatBubble.myMessage()) {
layoutResource = R.layout.left_chat_bubble;
} else {
layoutResource = R.layout.right_chat_bubble;
}
if (convertView != null) {
holder = (ViewHolder) convertView.getTag();
} else {
convertView = inflater.inflate(layoutResource, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}
//set message content
holder.msg.setText(ChatBubble.getContent());
return convertView;
}
#Override
public int getViewTypeCount() {
// return the total number of view types. this value should never change
// at runtime. Value 2 is returned because of left and right views.
return 2;
}
#Override
public int getItemViewType(int position) {
// return a value between 0 and (getViewTypeCount - 1)
return position % 2;
}
private class ViewHolder {
private TextView msg;
public ViewHolder(View v) {
msg = (TextView) v.findViewById(R.id.txt_msg);
}
}
}

Hashmap order inside the expandable listview varies from device to another

Now i'm making an application that it should display a list of courses in an expandable list view and when the user clicks on a child element it opens a new activity with the course details , everything works pretty fine but , when i tested the application through nexus the order of the courses was the same i put inside the hashmap and in the switch case statement but when i tested it through my galaxy not two here it came the disaster the orders in the list were scrambled so the click event got messed up when supposed to open course details for x it opens for y and so on ,,, what should i do ?
THIS IS THE MAIN
public class Courses extends ActionBarActivity {
HashMap<String,List<String>> Courses_castegory;
List<String> Courses_list;
ExpandableListView expandableListView;
MyCourseAdapter myCourseAdapter;
Intent detaledActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_courses);
expandableListView = (ExpandableListView) findViewById(R.id.simple_expandable_list);
Courses_castegory = CourseProvider.getInfo();
Courses_list=new ArrayList<>(Courses_castegory.keySet());//get all the keys from the hashmap
myCourseAdapter = new MyCourseAdapter(this,Courses_castegory,Courses_list);
expandableListView.setAdapter(myCourseAdapter);
expandableListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int groupPosition) {
Toast.makeText(getBaseContext(), Courses_list.get(groupPosition) + " is collapsed", Toast.LENGTH_SHORT).show();
}
});
expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
//Toast.makeText(getBaseContext(),
//Courses_castegory.get(Courses_list.get(groupPosition)).get(childPosition)+" from "+Courses_list.get(groupPosition)+" is selected",Toast.LENGTH_SHORT).show();
switch(groupPosition) {
case 0:
switch (childPosition) {
case 0:
detaledActivity = new Intent(Courses.this, DetailedCouse.class);
startActivity(detaledActivity);
break;
}
}
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_courses, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
THIS IS THE COURSE PROVIDER
public class CourseProvider {
public static HashMap<String,List<String>> getInfo(){
HashMap<String,List<String>>CourseDetails = new HashMap<String,List<String>>();
List<String> CourseType1 = new ArrayList<>();
CourseType1.add("English For Work");
List<String> CourseType2= new ArrayList<>();
CourseType2.add("General English For Work");
CourseType2.add("Intensive English For Work");
List<String> CourseType3 = new ArrayList<>();
CourseType3.add("English Academic Year");
CourseType3.add("English Academic Semester");
List<String> CourseType4 = new ArrayList<>();
CourseType4.add("IELTS Exam Preparation");
CourseType4.add("TOEFL Exam Preparation");
CourseType4.add("GMAT Exam Preparation");
CourseType4.add("GRE Exam Preparation");
List<String> CourseType5 = new ArrayList<>();
CourseType5.add("Young Learners");
List<String> CourseType6 = new ArrayList<>();
CourseType6.add("General English Language");
CourseType6.add("Intensive English Language");
CourseType6.add("30+");
CourseDetails.put("Learn English in Your Teacher's Home",CourseType1);
CourseDetails.put("English For Work",CourseType2);
CourseDetails.put("Academic Semester / Year",CourseType3);
CourseDetails.put("Exam Preparation Courses",CourseType4);
CourseDetails.put("Young Learners",CourseType5);
CourseDetails.put("Flexible Courses",CourseType6);
return CourseDetails;
}}
AND THIS IS THE COURSE ADAPTER
public class MyCourseAdapter extends BaseExpandableListAdapter {
private Context context;
private HashMap<String,List<String>>Courses_Category;
private List<String> Course_List ;
public MyCourseAdapter(Context context ,HashMap<String,List<String>>Courses_Category,List<String> Course_List) {
this.context=context;
this.Courses_Category=Courses_Category;
this.Course_List=Course_List;
}
#Override
public int getGroupCount() {
return Course_List.size();
}
#Override
public int getChildrenCount(int groupPosition) {
return Courses_Category.get(Course_List.get(groupPosition)).size();
}
#Override
public Object getGroup(int groupPosition) {
return Course_List.get(groupPosition);
}
#Override
public Object getChild(int parent, int child) {
return Courses_Category.get(Course_List.get(parent)).get(child);
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int parent, int child) {
return child;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
String group_title = (String) getGroup(groupPosition);
if (convertView==null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.parent_courses,parent,false);
}
TextView parent_textview = (TextView) convertView.findViewById(R.id.parent_text_view);
parent_textview.setTypeface(null, Typeface.BOLD);
parent_textview.setText(group_title);
return convertView;
}
#Override
public View getChildView(final int parentPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
String child_title = (String) getChild(parentPosition,childPosition);
if (convertView==null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView=inflater.inflate(R.layout.child_courses,parent,false);
}
TextView child_textview = (TextView) convertView.findViewById(R.id.child_text_view);
child_textview.setText(child_title);
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public void onGroupCollapsed(int groupPosition){
super.onGroupCollapsed(groupPosition);
}
public void onGroupExpanded(int groupPosition){
super.onGroupExpanded(groupPosition);
}}
//
Done using LinkedHashMapinstead of HashMap

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