我需要实现可扩展的ListView,但我在代码的getChildrenCount()
行的适配器中有空指针异常。
以下是适配器的代码:
public class DigitalMenuListAdapter extends BaseExpandableListAdapter {
private Context _context;
private ArrayList<ProductCategory> _listDataHeader; // header titles
// child data in format of header title, child title
// private HashMap<String, ArrayList<Products>> _listDataChild;
private ProductCategory productCategory;
private Products products;
private HashMap<String, ArrayList<Products>> productsList;
public DigitalMenuListAdapter(Context context, ArrayList<ProductCategory> productCategoryList,
HashMap<String, ArrayList<Products>> listDataForChild) {
this._context = context;
this._listDataHeader = productCategoryList;
this.productsList = listDataForChild;
}
@Override
public Object getChild(int groupPosition, int childPosititon) {
return null;
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
@Override
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
//final String childText = (String) getChild(groupPosition, childPosition);
products = productsList.get(childPosition).get(childPosition);
final String childText = products.getName();
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.digital_menu_list_item, null);
}
TextView txtListChild = (TextView) convertView
.findViewById(R.id.lblListItem);
txtListChild.setText(childText);
return convertView;
}
@Override
public int getChildrenCount(int groupPosition) {
return this.productsList.get(groupPosition).size(); }
@Override
public Object getGroup(int groupPosition) {
return this._listDataHeader.get(groupPosition);
}
@Override
public int getGroupCount() {
return this._listDataHeader.size();
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
// String headerTitle = (String) getGroup(groupPosition);
productCategory = _listDataHeader.get(groupPosition);
String headerTitle = productCategory.getName();
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.digital_menu_list_group, null);
}
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.lblListHeader);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
return convertView;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
以下是主要活动的代码,我从服务器获取数据,解析JSON,然后将数据设置为模式,listview,hashmap和适配器。
ProductsCategory是父可扩展ListView数据的模型,Products是子ListView数据的模型。
public class LocationMenuFragment extends Fragment {
private String locationId;
// Shared Preferences
private PreferencesManager mPrefs;
// Hash
private String hash;
private HttpEntity resEntity;
private String response_str, accesToken, id;
//UI
private ExpandableListView elvDigitalMenu;
private DigitalMenuListAdapter listAdapter;
//Models and Lists
private ProductCategory productCategory;
private ArrayList<ProductCategory> productCategoryList = new ArrayList<ProductCategory>();
private Products products;
private ArrayList<Products> productsList;
private HashMap<String, ArrayList<Products>> listDataForChild = new HashMap<String, ArrayList<Products>>();
public LocationMenuFragment init(String id) {
LocationMenuFragment fragment = new LocationMenuFragment();
// Supply val input as an argument.
Bundle args = new Bundle();
args.putString("id", id);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
locationId = getArguments() != null ? getArguments().getString("id")
: "";
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_location_menu,
container, false);
getData();
//UI
elvDigitalMenu = (ExpandableListView) rootView.findViewById(R.id.elv_digital_menu);
new SendDataToServer().execute(locationId);
//init adapter
//set adapter
//elvDigitalMenu.setAdapter(listAdapter);
return rootView;
}
// Get Location ID from LocationListActivity class and get accesToken
private void getData() {
mPrefs = new PreferencesManager(getActivity());
accesToken = mPrefs.getAccesToken();
}
private void getDigitalMenu(String id) {
getHash();
Log.d("Hash", hash);
String urlString = URLManager.DIGITAL_MENU + accesToken + "&hash="
+ hash;
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
StringBody sbId = new StringBody(id);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("id", sbId);
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
resEntity = response.getEntity();
response_str = EntityUtils.toString(resEntity);
if (resEntity != null) {
Log.i("RESPONSE", response_str);
Log.d("TAG", "Response from server : n "+ response_str);
}
} catch (Exception ex) {
Log.e("Debug", "error: " + ex.getMessage(), ex);
}
}
private class SendDataToServer extends AsyncTask<String, Void, Void> {
@Override
protected Void doInBackground(String... params) {
getDigitalMenu(params[0].toString());
if(response_str != null){
try {
JSONArray jsonArray = new JSONArray(response_str);
for(int i=0;i<jsonArray.length();i++){
JSONObject jsonObj = jsonArray.getJSONObject(i);
String name = jsonObj.getString("name");
String description = jsonObj.getString("description");
Log.d("TAG", name);
productCategory = new ProductCategory(name, description);
productCategoryList.add(productCategory);
JSONArray productsArray = jsonObj.getJSONArray("products");
productsList = new ArrayList<Products>();
for(int j=0;j<productsArray.length();j++){
JSONObject productsObject = productsArray.getJSONObject(j);
String id = productsObject.getString("ID");
Log.d("TAG", id);
String productName = productsObject.getString("name");
String productDescription = productsObject.getString("description");
String imagesCount = productsObject.getString("imagesCount");
String recommendsCount = productsObject.getString("recommendsCount");
String userRecommended = productsObject.getString("userRecommended");
//fali images i recommends niz
products = new Products(id, productName, productDescription, imagesCount, recommendsCount, userRecommended);
productsList.add(products);
listDataForChild.put(name, productsList);
//productsList.clear();
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{
Log.d("TAG", "response null");
}
return null;
}
@Override
protected void onPostExecute(Void result) {
/*for(int i=0;i<productCategoryList.size();i++){
listDataForChild.put(productCategoryList.get(i).toString(), productsList);
}*/
ArrayList<Products> value;
for (Entry<String, ArrayList<Products>> entry : listDataForChild.entrySet()) {
String key = entry.getKey();
Log.d("TAG", "KEY: "+key);
value = entry.getValue();
for(int k=0;k<value.size();k++){
products = value.get(k);
Log.d("TAG", products.getName());
}
}
listAdapter = new DigitalMenuListAdapter(getActivity(), productCategoryList, listDataForChild);
elvDigitalMenu.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
super.onPostExecute(result);
}
}
private void getHash() {
String finalStringForHash = URLManager.DIGITAL_MENU;
HashSHA256 h = new HashSHA256();
try {
hash = HashSHA256.hashMac(finalStringForHash);
} catch (SignatureException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}