HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Shorten/optimize an ExpandableListView

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
shortenoptimizeexpandablelistview

Problem

I have an expandable list view:

```
public class ExListViewAdapter extends BaseExpandableListAdapter {

private Context context;

private ExpandableListView exv;

private String[] sportList;

private final int AVAILABLE = 3;

private String[][] childList = {
{ "Fifa Net Width", "Fifa Penalty Kick" },
{ "NBA Free Throw Line", "NBA 3pt Line" },
{ "Pitching Mound", "Base Distance" },
{ "Available in the Paid Version" },
{ "Available in the Paid Version" },
{ "Available in the Paid Version" },
{ "Available in the Paid Version" } };

private InputValues iv;

private int lastExpandedGroupPosition;

public ExListViewAdapter(Context context, ExpandableListView e) {
this.context = context;
this.iv = (InputValues) context;
this.sportList = iv.getResources().getStringArray(
R.array.sportsCategories);
this.exv = e;
}

@Override
public View getChildView(final int groupPos, final int childPos,
boolean isLastChild, View convertView, ViewGroup parent) {

Button tv = new Button(context);
tv.setText(childList[groupPos][childPos]);

if (groupPos < AVAILABLE) {
tv.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
iv.setPresetType(sportList[groupPos],
childList[groupPos][childPos]);
}

});
} else {
tv.setEnabled(false);
}
return tv;
}

@Override
public void onGroupExpanded(int groupPosition) {
if (groupPosition != lastExpandedGroupPosition) {
exv.collapseGroup(lastExpandedGroupPosition);
}

super.onGroupExpanded(groupPosition);
lastExpandedGroupPosition = groupPosition;
}

@Override
public int getChildrenCount(int groupPos) {

Solution

Data Sources

You have three different sources of your data....

  • sportList is an array of the group values, and it is pulled from R.array.sportsCategories.



  • private final int AVAILABLE = 3; is a constant defined in the class.



  • childList is declared as an array in the class, but has extra data.



The reality is that AVAILABLE should be calculated from sportList, and the childList should be pulled from R as well.

Naming Convention

Button tv = new Button(context);


tv is a bad name, and it is because you copy/paste code from a TextView based method. In IDE's it is really easy to rename variables, even if the code is copy/pasted. There is no excuse ... ;-)

Efficiency

Apart from the above, I can't see any significant inefficiencies that need to be rectified. This code is run very few times, and is a low priority for efficiency.

Code Snippets

Button tv = new Button(context);

Context

StackExchange Code Review Q#32793, answer score: 5

Revisions (0)

No revisions yet.