I have tabs with three different fragments. Attendance, Exam and Result. On some phones when the result fragment starts the application crashes saying.
java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.Object
android.content.Context.getSystemService(java.lang.String)' on a null
object reference
here is the logcat
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference
at android.view.LayoutInflater.from(LayoutInflater.java:220)
at com.bu.innovate.bustudentportal.Result_Class$ExampleAdapter.<init>(Result_Class.java:886)
at com.bu.innovate.bustudentportal.Result_Class$results.onPostExecute(Result_Class.java:544)
at com.bu.innovate.bustudentportal.Result_Class$results.onPostExecute(Result_Class.java:245)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5942)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
and the code its pointing to is this
public class Result_Class extends Fragment implements java.io.Serializable {
private AnimatedExpandableListView listView;
private ExampleAdapter adapter;
String url;
String url2;
String url3;
static String urladder = "Transcript.aspx";
static String urladder2 = "Result.aspx";
static String urladder3 = "Result_Exam.aspx";
HashMap<String, String> hashMaps;
List<String> semester = new ArrayList<>();
List<Result_Gdata> GPA = new ArrayList<>();
List<Result_data> data_for_gra = new ArrayList<>();
List<Result_data> loop_finder = new ArrayList<>();
List<String> semester2 = new ArrayList<>();
List<Result_Gdata> GPA2 = new ArrayList<>();
List<Result_data> data_for_gra2 = new ArrayList<>();
List<Result_data> loop_finder2 = new ArrayList<>();
View rootview;
int num = 0;
HashMap<String, List<Result_data>> listDataChild;
FileOutputStream outputStream;
FileOutputStream outputStream2;
FileInputStream inputStream;
FileInputStream inputStream2;
String filename = "newResultData";
String filename2 = "oldResultData";
List<Result_data> data_for_gra3 = null;
List<String> semesters3 = null;
List<Result_data> loop_finder3 = null;
List<Result_Gdata> GPA3 = null;
List<Result_data> data_for_gra4 = null;
List<String> semesters4 = null;
List<Result_data> loop_finder4 = null;
List<Result_Gdata> GPA4 = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
super.onCreate(savedInstanceState);
rootview = inflater.inflate(R.layout.anim_result_layout, container, false);
listView = (AnimatedExpandableListView) rootview.findViewById(R.id.listView);
hashMaps = Data.map;
listView.setDivider(null);
listView.setDividerHeight(0);
if (Data.mychoice == 1) {
num = 0;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
new result_getter_second().execute();
}
}, 1800);
} else {
Handler handlers2 = new Handler();
handlers2.postDelayed(new Runnable() {
#Override
public void run() {
new results().execute();
}
}, 2000);
}
return rootview;
}
private class result_getter_second extends AsyncTask<Void, Void, Void> {
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
num = 0;
listDataChild = new HashMap<>();
List<GroupItem> items = new ArrayList<>();
if (semester.size() != 0) {
for (int m = 0; m < semester.size(); m++) {
GroupItem item = new GroupItem();
item.title = semester.get(m);
if (m < GPA.size()) {
item.gpa = GPA.get(m).getGPA();
item.cgpa = GPA.get(m).getCGPA();
}
List<Result_data> datw = new ArrayList<>();
for (int n = num; n < loop_finder.get(m).getSize_of_the_result(); n++) {
ChildItem child = new ChildItem();
child.course = data_for_gra.get(n).getSubject();
child.grade = data_for_gra.get(n).getGrade();
item.items.add(child);
datw.add(new Result_data(data_for_gra.get(n).getSubject(), data_for_gra.get(n).getGrade()));
num++;
}
items.add(item);
if(getActivity()!=null)
{
adapter = new ExampleAdapter(getActivity()); // line number 544
adapter.setData(items);
listView.setAdapter(adapter);
}
listView.setOnGroupClickListener(new OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
if (listView.isGroupExpanded(groupPosition)) {
listView.collapseGroupWithAnimation(groupPosition);
} else {
listView.expandGroupWithAnimation(groupPosition);
}
return true;
}
});
}
}
}
}
private static class GroupItem {
String title;
String gpa;
String cgpa;
List<ChildItem> items = new ArrayList<ChildItem>();
}
private static class ChildItem {
String course;
String grade;
}
private static class ChildHolder {
TextView course;
TextView grade;
}
private static class GroupHolder {
TextView title;
TextView gpa;
TextView cgpa;
}
/**
* Adapter for our list of {#link GroupItem}s.
*/
private class ExampleAdapter extends AnimatedExpandableListView.AnimatedExpandableListAdapter {
private LayoutInflater inflater;
private List<GroupItem> items;
public ExampleAdapter(Context context) {
if(context!=null)
{
inflater = LayoutInflater.from(context); // line number 886
}
}
public void setData(List<GroupItem> items) {
this.items = items;
}
#Override
public ChildItem getChild(int groupPosition, int childPosition) {
return items.get(groupPosition).items.get(childPosition);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getRealChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
ChildHolder holder;
ChildItem item = getChild(groupPosition, childPosition);
if (childPosition == 0) {
holder = new ChildHolder();
convertView = inflater.inflate(R.layout.anim_list_item_result, parent, false);
holder.course = (TextView) convertView.findViewById(R.id.textcourse);
holder.grade = (TextView) convertView.findViewById(R.id.textgrade);
convertView.setTag(holder);
holder.course.setText(item.course);
holder.grade.setText(item.grade);
} else if (isLastChild) {
holder = new ChildHolder();
convertView = inflater.inflate(R.layout.anim_list_item_result_last_child, parent, false);
holder.course = (TextView) convertView.findViewById(R.id.textcourse);
holder.grade = (TextView) convertView.findViewById(R.id.textgrade);
convertView.setTag(holder);
holder.course.setText(item.course);
holder.grade.setText(item.grade);
} else {
holder = new ChildHolder();
convertView = inflater.inflate(R.layout.anim_list_item_result_middle, parent, false);
holder.course = (TextView) convertView.findViewById(R.id.textcourse);
holder.grade = (TextView) convertView.findViewById(R.id.textgrade);
convertView.setTag(holder);
holder.course.setText(item.course);
holder.grade.setText(item.grade);
}
return convertView;
}
#Override
public int getRealChildrenCount(int groupPosition) {
return items.get(groupPosition).items.size();
}
#Override
public GroupItem getGroup(int groupPosition) {
return items.get(groupPosition);
}
#Override
public int getGroupCount() {
return items.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
GroupHolder holder;
GroupItem item = getGroup(groupPosition);
if (groupPosition == getGroupCount() - 1) {
holder = new GroupHolder();
convertView = inflater.inflate(R.layout.anim_group_item_result_last_child, parent, false);
holder.title = (TextView) convertView.findViewById(R.id.textTitle);
holder.gpa = (TextView) convertView.findViewById(R.id.textgpa);
holder.cgpa = (TextView) convertView.findViewById(R.id.textcgpa);
convertView.setTag(holder);
holder.title.setText(item.title);
holder.gpa.setText(item.gpa);
holder.cgpa.setText(item.cgpa);
} else {
holder = new GroupHolder();
convertView = inflater.inflate(R.layout.anim_group_item_result, parent, false);
holder.title = (TextView) convertView.findViewById(R.id.textTitle);
holder.gpa = (TextView) convertView.findViewById(R.id.textgpa);
holder.cgpa = (TextView) convertView.findViewById(R.id.textcgpa);
convertView.setTag(holder);
holder.title.setText(item.title);
holder.gpa.setText(item.gpa);
holder.cgpa.setText(item.cgpa);
}
if (groupPosition == 0) {
ExpandableListView elv = (ExpandableListView) parent;
elv.expandGroup(groupPosition);
}
return convertView;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public boolean isChildSelectable(int arg0, int arg1) {
return true;
}
}
private boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
//should check null because in air plan mode it will be null
return (netInfo != null && netInfo.isConnected());
}
}
The problem is in the first line where the getcontext() is called I have tried so much to solve this problem but couldn't. It would be really helpful If you guys help me solve this problem.
Does you make it onCreate in fragment?
Add checking for getContext()!=null
Before block
adapter = new ExampleAdapter(getContext());
adapter.setData(items);
listView.setAdapter(adapter);
And better replace for getActivity()!=null
For example:
if (getActivity()!=null){
adapter = new ExampleAdapter(getActivity());
adapter.setData(items);
listView.setAdapter(adapter);
}
Related
I have implemented a Expandable List View,in Android , you can see in the screenshot , it is working fine , and in Expandable List i have multiple child with delete option in group as you can see in the screen shot, i want to delete a particular child which user has selected to delete , I am not able to delete the child form Expandable List , i will post my code , please anyone guide me
public class PendingFragment extends Fragment {
private AnimatedExpandableListView listView;
private PendingAdapter adapter;
CoordinatorLayout coordinatorLayout;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_pending, container, false);
coordinatorLayout = (CoordinatorLayout)view.findViewById(R.id.pending_frag_coordinatorLayout);
List<GroupItem> items = new ArrayList<GroupItem>();
// Populate our list with groups and it's children
for(int i = 1; i < 10; i++) {
GroupItem item = new GroupItem();
item.title = "GroupItem " + i;
for(int j = 0; j < i; j++) {
ChildItem child = new ChildItem();
child.title = "ChildItem " + j;
item.items.add(child);
}
items.add(item);
}
adapter = new PendingAdapter(getActivity());
adapter.setData(items);
listView = (AnimatedExpandableListView)view.findViewById(R.id.pending_explistView);
listView.setAdapter(adapter);
return view;
}
}
My Listview Adapter
public class PendingAdapter extends AnimatedExpandableListView.AnimatedExpandableListAdapter {
private LayoutInflater inflater;
private List<GroupItem> items;
ListPopupWindow listPopupWindow;
String[] products = {"Delete"};
Context contexts;
public PendingAdapter(Context context) {
inflater = LayoutInflater.from(context);
this.contexts = context;
}
public void setData(List<GroupItem> items) {
this.items = items;
}
private class ChildHolder {
TextView title;
ImageView option_menu;
}
private class GroupHolder {
TextView title;
}
#Override
public ChildItem getChild(int groupPosition, int childPosition) {
return items.get(groupPosition).items.get(childPosition);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getRealChildView(final int groupPosition,final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
ChildHolder holder;
ChildItem item = getChild(groupPosition, childPosition);
Log.e("groupPosition=" + groupPosition, "childPosition=" + childPosition);
if (convertView == null) {
holder = new ChildHolder();
convertView = inflater.inflate(R.layout.expchildlistview, parent, false);
holder.title = (TextView) convertView.findViewById(R.id.txtListChild);
holder.option_menu = (ImageView) convertView.findViewById(R.id.checkin_option_menu);
convertView.setTag(holder);
} else {
holder = (ChildHolder) convertView.getTag();
}
holder.title.setText(item.title);
holder.option_menu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ShowListMenu(view,groupPosition, childPosition);
}
});
return convertView;
}
public void ShowListMenu(View v, final int childPosition, final int groupPosition){
listPopupWindow = new ListPopupWindow(contexts);
listPopupWindow.setAdapter(new ArrayAdapter(contexts, android.R.layout.simple_list_item_1, products));
listPopupWindow.setAnchorView(v);
if (Utils.device_width(contexts) >= 320 && Utils.device_width(contexts) < 480) {
//Log.v(">= 320 < 480=", ">= 320 < 480");
listPopupWindow.setWidth(150);
}else if (Utils.device_width(contexts) >= 480 && Utils.device_width(contexts) < 500) {
//Log.v(">= 480=", "< 500");
listPopupWindow.setWidth(150);
}else{
listPopupWindow.setWidth(200);
}
listPopupWindow.setModal(true);
listPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Log.v("item.remove=", "" + items.get(groupPosition).items.get(childPosition));
items.get(groupPosition).items.remove(childPosition);
notifyDataSetChanged();
listPopupWindow.dismiss();
}
});
listPopupWindow.show();
}
#Override
public int getRealChildrenCount(int groupPosition) {
return items.get(groupPosition).items.size();
}
#Override
public GroupItem getGroup(int groupPosition) {
return items.get(groupPosition);
}
#Override
public int getGroupCount() {
return items.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
GroupHolder holder;
GroupItem item = getGroup(groupPosition);
if (convertView == null) {
holder = new GroupHolder();
convertView = inflater.inflate(R.layout.explist_group, parent, false);
holder.title = (TextView) convertView.findViewById(R.id.lblListHeader);
convertView.setTag(holder);
} else {
holder = (GroupHolder) convertView.getTag();
}
holder.title.setText(item.title);
return convertView;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public boolean isChildSelectable(int arg0, int arg1) {
return true;
}
}
public class GroupItem {
public String title;
public List<ChildItem> items = new ArrayList<ChildItem>();
}
public class ChildItem {
public String title;
}
Cant see items.remove(child) on click on delete. I think you should try deleting the child from the list and than set the adapter with updated values. #Achin
I have listview in a listview on scrolling the inner listview content goes empty ,i am getting tags still getting problem, so to save the data i saved it list values in hasmap and getting from there. but one list value is saved not other ,any one please give me clue or solution how to get the value from "finish data list" as geting "unit" from "item" list and "feet" from "finish" data list or any other problem in my below code
public class ViewAdapter extends BaseExpandableListAdapter {
private int lastExpandedGroupPosition;
private ExpandableListView expandableListView;
private LayoutInflater inflater;
private List<String> groupItems;
private HashMap<String, List<String>> childItems;
public int childCount = 0;
private Context context;
private List<List<String>> firstLevelItems;
HashMap<String, List<String>> firstLevelItems1;
private List<String> endData;
private HashMap<String, String> endHashmap;
private List<List<String>> finishData;
private int finishDataPosition;
private List<String> photos;
private int lengthCounter;
private int someCounter;
public ViewAdapter(Context context, ExpandableListView listView, List<String> groupItems) {
if (listView != null)
expandableListView = listView;
if (context != null)
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (groupItems != null && !groupItems.isEmpty())
this.groupItems = groupItems;
childItems = new HashMap<>();
firstLevelItems1 = new HashMap<>();
firstLevelItems = new ArrayList<>();
endData = new ArrayList<>();
endHashmap = new HashMap<>();
finishData = new ArrayList<>();
photos = new ArrayList<>();
this.context = context;
ImageLoaderInit(context);
lengthCounter = 0;
}
#Override
public int getGroupCount() {
return groupItems.size();
}
#Override
public int getChildrenCount(int groupPosition) {
return childCount;
}
#Override
public Object getGroup(int groupPosition) {
return null;
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return null;
}
#Override
public long getGroupId(int groupPosition) {
return 0;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return 0;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
View view = convertView;
ViewHolder vh = null;
;
if (view == null) {
vh = new ViewHolder();
view = inflater.inflate(R.layout.view_main_group_item, parent, false);
vh.title = (TextView) view.findViewById(R.id.view_main_group_title);
vh.arrow = (ImageView) view.findViewById(R.id.view_main_group_arrow);
view.setTag(vh);
} else
vh = (ViewHolder) view.getTag();
if (isExpanded) {
view.setPadding(0, 0, 0, 0);
lastExpandedGroupPosition = groupPosition;
vh.arrow.setImageResource(R.drawable.icon_down_10);
} else {
view.setPadding(0, 0, 0, 15);
}
vh.title.setText(groupItems.get(groupPosition));
return view;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
View view = convertView;
ViewHolder vh = null;
if (view == null) {
vh = new ViewHolder();
view = inflater.inflate(R.layout.view_main_child_item, parent, false);
vh.title = (TextView) view.findViewById(R.id.view_main_child_item);
vh.photoLayout = (LinearLayout) view.findViewById(R.id.view_main_child_bottom_layout);
vh.firstLevelItemsLV = (ListView) view.findViewById(R.id.view_main_child_first_level_items);
/* if (childPosition < childCount - 1) {
vh.photoLayout.setVisibility(View.GONE);
} else*/ {
vh.firstPhoto = (ImageView) view.findViewById(R.id.view_main_first_photo);
vh.secondPhoto = (ImageView) view.findViewById(R.id.view_main_second_photo);
vh.thirdPhoto = (ImageView) view.findViewById(R.id.view_main_third_photo);
vh.thirdPhoto.setImageResource(R.drawable.default1);
vh.secondPhoto.setImageResource(R.drawable.default1);
vh.firstPhoto.setImageResource(R.drawable.default1);
}
view.setTag(vh);
} else {
vh = (ViewHolder) view.getTag();
}
if (childItems.get(groupPosition + "") != null && !childItems.get(groupPosition + "").isEmpty()) {
String s = "• " + childItems.get(groupPosition + "").get(childPosition) + " :";
vh.title.setText(s);
}
for (int i = 0; i < firstLevelItems.get(childPosition).size(); i++) {
if (finishData.size() > (lengthCounter)) {
if (finishData.get(lengthCounter).size() > someCounter) {
someCounter = finishData.get(lengthCounter).size() + 1;
}
} else
// someCounter = finishData.get(finishData.get(lengthCounter).size()-1).size();
/*{
{
}
}*/lengthCounter++;
}
int i = firstLevelItems.get(childPosition).size();
Log.i("size ", i + "");
// someCounter= finishData.get(finishDataPosition).size()+2;
Log.e("LENGTH", "Child: " + lengthCounter);
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
float oneItemDp1 = display.getHeight();
float oneItemDp = oneItemDp1 / 65;
// float oneItemDp = 40 / context.getResources().getDisplayMetrics().density;
int heighy = (int) oneItemDp * (firstLevelItems.get(childPosition).size() +
i + 1);
vh.firstLevelItemsLV.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, heighy
));
someCounter = 0;// by me
ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams) vh.firstLevelItemsLV.getLayoutParams();
mlp.setMargins(30, 0, 0, 0);
FirstLevelAdapter firstAdapter = new FirstLevelAdapter(context, firstLevelItems.get(childPosition));
vh.firstLevelItemsLV.setAdapter(firstAdapter);
if (vh.firstPhoto != null) {
vh.firstPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (photos.size() >= 1) {
Intent intent = new Intent(context, EnlargeImageActivity.class);
String photo1 = photos.get(0);
intent.putExtra("photo1", photo1);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
} else
Toast.makeText(context, "New image to show", Toast.LENGTH_SHORT).show();
;
}
});
}
if (vh.secondPhoto != null) {
vh.secondPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (photos.size() >= 2) {
Intent intent = new Intent(context, EnlargeImageActivity.class);
String photo1 = photos.get(1);
intent.putExtra("photo1", photo1);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
} else
Toast.makeText(context, "New image to show", Toast.LENGTH_SHORT).show();
;
}
});
}
if (vh.thirdPhoto != null) {
vh.thirdPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (photos.size() >= 3) {
Intent intent = new Intent(context, EnlargeImageActivity.class);
String photo1 = photos.get(2);
intent.putExtra("photo1", photo1);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
} else {
Toast.makeText(context, "New image to show", Toast.LENGTH_SHORT).show();
;
}
}
});
}
if (vh.firstPhoto != null) {
if (photos.size() >= 1) {
if (!this.photos.isEmpty()) {
vh.firstPhoto.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageLoader.displayImage("file://" + Uri.parse(this.photos.get(0)), vh.firstPhoto, imageOptions);
}
} else {
vh.firstPhoto.setImageResource(R.drawable.default1);
}
}
if (vh.secondPhoto != null) {
if (photos.size() >= 2) {
if (this.photos.size() > 1 && !this.photos.isEmpty()) {
vh.secondPhoto.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageLoader.displayImage("file://" + Uri.parse(this.photos.get(1)), vh.secondPhoto, imageOptions);
}
} else {
//vh.secondPhoto.setImageDrawable(context.getResources().getDrawable(R.drawable.icon_save));
//vh.secondPhoto.setMaxHeight(100);
vh.secondPhoto.setImageResource(R.drawable.default1);
}
}
if (vh.thirdPhoto != null) {
if (photos.size() >= 3) {
if (this.photos.size() > 2 && !this.photos.isEmpty()) {
vh.thirdPhoto.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageLoader.displayImage("file://" + Uri.parse(this.photos.get(2)), vh.thirdPhoto, imageOptions);
}
} else {
vh.thirdPhoto.setImageResource(R.drawable.default1);
}
}
return view;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
#Override
public void onGroupExpanded(final int groupPosition) {
if (groupPosition != lastExpandedGroupPosition) {
expandableListView.collapseGroup(lastExpandedGroupPosition);
}
super.onGroupExpanded(groupPosition);
lastExpandedGroupPosition = groupPosition;
}
public void setChildView(int groupPosition, List<String> childItems, List<List<String>> firstLevelItems,
List<String> endData, List<List<String>> photos) {
if (childItems != null && !childItems.isEmpty()) {
childCount = childItems.size();
this.childItems.put(groupPosition + "", childItems);
}
if (firstLevelItems != null && !firstLevelItems.isEmpty()) {
this.firstLevelItems.clear();
this.firstLevelItems.addAll(firstLevelItems);
// firstLevelItems1.put(groupPosition + "", firstLevelItems);
}
if (endData != null && !endData.isEmpty()) {
finishData.clear();
finishDataPosition = 0;
someCounter = 0;
for (int i = 0; i < endData.size(); i++) {
List<String> tempList = new ArrayList<>();
List<String> splitedList = new ArrayList<>();
tempList = Arrays.asList(endData.get(i).split("\\|"));
for (int j = 0; j < tempList.size(); j++) {
if (!tempList.get(j).contains("Other")) {
if (!tempList.get(j).contains("Comment Box")) {
splitedList.add(/*Arrays.asList(*/tempList.get(j)/*.split(":"))*/);
}
}
}
finishData.add(splitedList);
}
}
List<String> tempPhotoList = new ArrayList<>();
if (photos != null && !photos.isEmpty()) {
this.photos.clear();
for (int i = 0; i < photos.size(); i++) {
for (int x = 0; x < photos.get(i).size(); x++) {
tempPhotoList.addAll(Arrays.asList(photos.get(i).get(x).split("\\|")));
}
}
List<String> photoBuffer = new ArrayList<>();
for (String name : tempPhotoList) {
if (name.contains(".ABCInventory")) {
photoBuffer.add(name);
Log.e("TAG", name);
}
}
this.photos = photoBuffer;
}
}
private class FirstLevelAdapter extends BaseAdapter {
private LayoutInflater inflater;
private List<String> items;
private Context _context;
private SharedPreferences sharedPreferences;
private String firstLevel;
private ModelData md;
private String s1;
HashMap<Integer, View> hashMap = new HashMap<Integer, View>();
public FirstLevelAdapter(Context context, List<String> objects) {
if (objects != null) {
items = objects;
}
_context = context;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder vh=null;
if (items != null && !items.isEmpty()) {
firstLevelItems1.put(position + "", items);
}
if (convertView == null) {
md = new ModelData();
/* if (hashMap.containsKey(position)) {
return hashMap.get(position);
}*/
try {
{
s1 = "• " + firstLevelItems1.get(position + "").get(position) + " :" ;
md.finalFirtstLevel = s1;
}
}catch(Exception e)
{
e.printStackTrace();
}
vh = new ViewHolder();
convertView = inflater.inflate(R.layout.view_main_child_second_item, parent, false);
vh.item = (TextView) convertView.findViewById(R.id.child_second_item);
vh.elements = (ListView) convertView.findViewById(R.id.child_third_level_items);
// vh.item.setText(s);
vh.item.setText(md.finalFirtstLevel);
convertView.setTag(vh);
/* hashMap.put(position, convertView);*/
} else {
vh = (ViewHolder) convertView.getTag();
}
if (finishData.size() > (finishDataPosition)) // by me
if (finishData.get(finishDataPosition).size() < 2) {
String[] split = finishData.get(finishDataPosition).get(0).split(":");
for (int i = 0; i < finishData.get(finishDataPosition).size(); i++) {
Log.i("split value ", finishData.get(finishDataPosition).get(i) + split[1] + " finishDataPosition " + finishDataPosition);
}
if (split[1] != null && !split[1].isEmpty()) {
md = new ModelData();
String s = "• " + firstLevelItems1.get(position + "").get(position) + " :" + split[1];
md.finalFirtstLevel = s;
vh.item.setText(md.finalFirtstLevel);
}
} else {
md = new ModelData();
String s = "• " + firstLevelItems1.get(position + "").get(position) + " :" ;
md.finalFirtstLevel1 = s;
vh.item.setText(md.finalFirtstLevel1);
float oneItemDp = 10 / _context.getResources().getDisplayMetrics().density;
Log.e("LENGTH", "Adapter: " + lengthCounter);
vh.elements.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
(int) oneItemDp * someCounter));
ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams) vh.elements
.getLayoutParams();
mlp.setMargins(30, 0, 0, 0);
// vh.elements.setAdapter(new FinishDataAdapter(finishData.get(finishDataPosition)));
}
finishDataPosition++;
return convertView;
}
;
public class ModelData {
public String finalFirtstLevel = "";
public String finalFirtstLevel1 = "";
}
}
private class FinishDataAdapter extends BaseAdapter {
private LayoutInflater inflater;
private List<String> items;
public FinishDataAdapter(List<String> objects) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
items = objects;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = inflater.inflate(R.layout.view_main_child_finish_item, parent, false);
TextView item = (TextView) view.findViewById(R.id.child_finish_item);
item.setText("• " + items.get(position));
return view;
}
}
private ImageLoader imageLoader;
private DisplayImageOptions imageOptions;
private void ImageLoaderInit(Context context) {
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
.memoryCache(new LruMemoryCache(10 * 1024 * 1024))
.memoryCacheSize(50 * 1024 * 1024)
.memoryCacheSizePercentage(20)
.diskCacheSize(300 * 1024 * 1024)
.diskCacheFileCount(375)
.diskCacheFileNameGenerator(new Md5FileNameGenerator())
.defaultDisplayImageOptions(DisplayImageOptions.createSimple())
.build();
imageOptions = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.default1)
.resetViewBeforeLoading(false)
.delayBeforeLoading(0)
.cacheInMemory(true)
.cacheOnDisc(true)
.considerExifParams(true)
.imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
.bitmapConfig(Bitmap.Config.RGB_565)
.displayer(new SimpleBitmapDisplayer())
.handler(new Handler())
.build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
}
private class ViewHolder {
ImageView arrow = null;
LinearLayout photoLayout;
ListView firstLevelItemsLV;
TextView title = null;
TextView title1 = null;
ImageView firstPhoto;
ImageView secondPhoto;
TextView item;
ImageView thirdPhoto;
ListView elements;
}
}
When I click on the child views on my app it does not respond to the click. I pretty much googled this as much as I could without any success. I tried debugging it and when I touch the child it does not go in the onclick method
Activity class
public class LetestNews extends ExpandableListActivity{
private ArrayList<String> parentItems = new ArrayList<String>();
private ArrayList<Object> childItems = new ArrayList<Object>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// this is not really necessary as ExpandableListActivity contains an ExpandableList
//setContentView(R.layout.main);
ExpandableListView expandableList = getExpandableListView(); // you can use (ExpandableListView) findViewById(R.id.list)
expandableList.setDividerHeight(2);
expandableList.setGroupIndicator(null);
expandableList.setClickable(true);
setGroupParents();
setChildData();
ExpandableAdapter adapter = new ExpandableAdapter(parentItems, childItems);
adapter.setInflater((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE), this);
expandableList.setAdapter(adapter);
//expandableList.setOnChildClickListener(this);
expandableList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
public boolean onChildClick(ExpandableListView parent, View v,int groupPosition, int childPosition, long id) {
/* You must make use of the View v, find the view by id and extract the text as below*/
Toast.makeText(getBaseContext(), "Shaan is a monkey",
Toast.LENGTH_SHORT).show();
return true; // i missed this
}
});
}
public void setGroupParents() {
try {
FileInputStream newsIn = openFileInput("news.txt");
String newsObj = "";
String objEnc="";
Gson gson=new Gson();
BufferedReader inputNews = new BufferedReader(new InputStreamReader(newsIn, "UTF-8"));
StringBuilder sbuilderNews = new StringBuilder();
newsObj = inputNews.readLine();
while (newsObj != null) {
sbuilderNews.append(newsObj);
newsObj = inputNews.readLine();
if (newsObj != null) {
// sbuilder.append("\n");
}
}
newsIn.close();
newsObj = sbuilderNews.toString();
SubredditNews objNews = gson.fromJson(newsObj, SubredditNews.class);
ArrayList<SubredditIN>subredditObjects=objNews.subreddits;
for(int i=0;i<subredditObjects.size();i++){
parentItems.add(subredditObjects.get(i).name);
}
}catch(Exception e){
}
}
public void setChildData() {
// Android
ArrayList<String> child = new ArrayList<String>();
String a="";
/*child.add("Core");
child.add("Games");
childItems.add(child);*/
try {
FileInputStream newsIn = openFileInput("news.txt");
String newsObj = "";
String objEnc="";
Gson gson=new Gson();
BufferedReader inputNews = new BufferedReader(new InputStreamReader(newsIn, "UTF-8"));
StringBuilder sbuilderNews = new StringBuilder();
newsObj = inputNews.readLine();
while (newsObj != null) {
sbuilderNews.append(newsObj);
newsObj = inputNews.readLine();
if (newsObj != null) {
// sbuilder.append("\n");
}
}
newsIn.close();
newsObj = sbuilderNews.toString();
SubredditNews objNews = gson.fromJson(newsObj, SubredditNews.class);
ArrayList<SubredditIN>subredditObjects=objNews.subreddits;
for(int i=0;i<objNews.subreddits.size();i++){
child = new ArrayList<String>();
for(int j=0;j<objNews.subreddits.get(i).posts.size();j++) {
subredditObjects.get(i).setURL();
a=subredditObjects.get(i).getPostLink();
child.add(objNews.subreddits.get(i).posts.get(j));
Log.i("this is the link", a);
}
childItems.add(child);
}
}catch(Exception e){
String dd="";
}
}
}
Adapter class
public class ExpandableAdapter extends BaseExpandableListAdapter {
private Activity activity;
private ArrayList<Object> childtems;
private LayoutInflater inflater;
private ArrayList<String> parentItems, child;
public ExpandableAdapter(ArrayList<String> parents, ArrayList<Object> childern) {
this.parentItems = parents;
this.childtems = childern;
}
public void setInflater(LayoutInflater inflater, Activity activity) {
this.inflater = inflater;
this.activity = activity;
}
#Override
public View getChildView(int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
child = (ArrayList<String>) childtems.get(groupPosition);
TextView textView = null;
if (convertView == null) {
convertView = inflater.inflate(R.layout.group, null);
}
textView = (TextView) convertView.findViewById(R.id.textView1);
textView.setText(child.get(childPosition));
//textView.setText(Html.fromHtml("<a href=http://www.stackoverflow.com> STACK OVERFLOW "));
// textView.setMovementMethod(LinkMovementMethod.getInstance());
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(activity, child.get(childPosition),
Toast.LENGTH_SHORT).show();
}
});
return convertView;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.child, null);
}
((CheckedTextView) convertView).setText(parentItems.get(groupPosition));
((CheckedTextView) convertView).setChecked(isExpanded);
return convertView;
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return null;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return 0;
}
#Override
public int getChildrenCount(int groupPosition) {
return ((ArrayList<String>) childtems.get(groupPosition)).size();
}
#Override
public Object getGroup(int groupPosition) {
return null;
}
#Override
public int getGroupCount() {
return parentItems.size();
}
#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 boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
I have the following two class one is fragment class and another one is custom expandablelistadapter class. i want the values fetch from the expandablelistadapter class and set the values into fragment UI component like set into textview i describe as comment in following class where to taken values
and where to set the values
SlideContentFragment.java
public class SlidingContentFragment extends Fragment {
static final String LOG_TAG = "SlidingContentFragment";
// store category list from Conastant list, used for to display pagetitle
List<String> catList = AppConstants.CATEGORY_LIST;
private static String[] tmpId = {"35","36","41","42","43","44","45","46"};
ExpandableListView exListCategory;
private SlidingTabLayout mSlidingTabLayout;
/**
* A {#link android.support.v4.view.ViewPager} which will be used in conjunction with the {#link SlidingTabLayout} above.
*/
private ViewPager mViewPager;
//private ExpandableListAdapter mAdapter; // added new
private SamplePagerAdapter myAdapter;
public SlidingContentFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_sliding_content, container, false);
ImageButton cartImgBtn = (ImageButton)v.findViewById(R.id.imgBtnCart);
TextView totalCntItem = (TextView)v.findViewById(R.id.tvCartItemCount);
// I want here set the value of totalCounter from ExpandableList Adapter class when i click on plus
// OR minus button of particular item it updates its value as total count of all item selected
// here following line of code which not worked
totalCntItem.setText(String.format("%d",CategoryItemListAdapter.getTotalCounter()));
return v;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// BEGIN_INCLUDE (setup_viewpager)
// Get the ViewPager and set it's PagerAdapter so that it can display items
this.myAdapter = new SamplePagerAdapter(); // added new
mViewPager = (ViewPager) view.findViewById(R.id.viewpager);
mViewPager.setAdapter(this.myAdapter);
// END_INCLUDE (setup_viewpager)
// BEGIN_INCLUDE (setup_slidingtablayout)
// Give the SlidingTabLayout the ViewPager, this must be done AFTER the ViewPager has had
// it's PagerAdapter set.
mSlidingTabLayout = (SlidingTabLayout) view.findViewById(R.id.sliding_tabs);
mSlidingTabLayout.setViewPager(mViewPager);
}
public class SamplePagerAdapter extends PagerAdapter {
public SamplePagerAdapter() {
super();
}
#Override
public int getCount() {
return catList.size();
}
#Override
public boolean isViewFromObject(View view, Object o){
return o == view;
}
#Override
public CharSequence getPageTitle(int position) {
return catList.get(position);
}
#Override
public int getItemPosition (Object object)
{
return PagerAdapter.POSITION_NONE;
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
//return super.instantiateItem(container, position);
ViewPager viewPager = (ViewPager)container;
View view = getActivity().getLayoutInflater().inflate(R.layout.pager_item,
container, false);
viewPager.addView(view);
exListCategory = (ExpandableListView)view.findViewById(R.id.myExpandableListView);
//exListCategory.setIndicatorBounds(10,20);
exListCategory.setDividerHeight(2);
if(ConnectionDetector.isInternetAvailable(getActivity())) {
new CategoryJSONAsyncTask().execute("http://..../api/Main/GetCateenOrderCategoryItemListDetail?CategoryID=" + tmpId[position].trim());
}else{
Utility.buildDialog(getActivity()).show();
}
Log.i(String.format("%s: POSITION", LOG_TAG), String.valueOf(position));
Log.i(String.format("%s: CATLIST", LOG_TAG),String.valueOf(catList.get(position)));
view.setTag(position);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
//viewpager
ViewPager viewPager = (ViewPager)container;
View view = (View) object;
view.getTag(position);
viewPager.removeView(view);
//((ViewPager) container).removeView((View) object);
}
}
public class CategoryJSONAsyncTask extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String result = "";
try {
HttpGet httppost = new HttpGet(params[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity);
return result;
}
return result;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ArrayList<CategoryParentItemList> listParent = fetchResponse(result.replace("\n","").trim());
/*for (Object obj : listParent){
if(obj.getClass() == CategoryParentItemList.class){
CategoryParentItemList p = (CategoryParentItemList)obj;
System.out.println("P-ItemName: "+ p.subCategoryName);
}
}*/
CategoryItemListAdapter adapter = new CategoryItemListAdapter(SlidingContentFragment.this.getActivity(), listParent);
exListCategory.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
public ArrayList<CategoryParentItemList> fetchResponse(String result)
{
ArrayList<CategoryParentItemList> listParent = new ArrayList<>();
if (!result.equals(""))
{
try
{
JSONObject jsono = new JSONObject(result);
JSONArray jarray = jsono.getJSONArray("SBL");
CategoryParentItemList parent;
for (int i = 0; i < jarray.length(); i++)
{
ArrayList<CategoryChildListItem> childrens = new ArrayList<>();
childrens.clear();
CategoryChildListItem child;
JSONObject object = jarray.getJSONObject(i);
//System.out.println("SCI: " + object.getInt("SubCategoryID"));
//System.out.println("SCN: " + object.getString("SubCategoryName"));
JSONArray subItemArray = object.getJSONArray("SubCategoryItemList");
if (subItemArray.length() > 0)
{
for (int j = 0; j < subItemArray.length(); j++)
{
JSONObject subItemObject = subItemArray.getJSONObject(j);
String strItemName = subItemObject.getString("ItemName");
String strDefaultPrice = subItemObject.getString("DefaultPrice");
child = new CategoryChildListItem(strItemName, strDefaultPrice);
childrens.add(child);
//Log.i("strItemName", strItemName);
//Log.i("strDefaultPrice", strDefaultPrice);
}
parent = new CategoryParentItemList(object.getString("SubCategoryName"),childrens);
listParent.add(parent);
}
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
return listParent;
}
}
CategoryListItemAdaptor.java
public class CategoryItemListAdapter extends BaseExpandableListAdapter{
private Context context;
public static int totalCounter=0;
private ArrayList<CategoryParentItemList> listParent;
static class ViewHolderGroup {
public TextView lblSubCategoryName;
}
static class ViewHolderChild {
public TextView lblItemName;
public TextView lblDefualtPrice;
public TextView lblQty;
public ImageButton imgPlus;
public ImageButton imgMinus;
}
public CategoryItemListAdapter(Context context, ArrayList<CategoryParentItemList> listParent) {
super();
this.context = context;
this.listParent = listParent;
}
#Override
public int getGroupCount() {
return listParent.size();
}
#Override
public int getChildrenCount(int groupPosition) {
ArrayList<CategoryChildListItem> ch = listParent.get(groupPosition).getChildList();
return ch.size();
}
#Override
public Object getGroup(int groupPosition) {
return listParent.get(groupPosition);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
ArrayList<CategoryChildListItem> ch = listParent.get(groupPosition).getChildList();
return ch.get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
//CategoryParentItemList parentItem = (CategoryParentItemList)listParent.get(groupPosition);
CategoryParentItemList parentItem = (CategoryParentItemList) getGroup(groupPosition);
ViewHolderGroup holderGroup;
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.group_header, null);
holderGroup = new ViewHolderGroup();
holderGroup.lblSubCategoryName = (TextView) convertView.findViewById(R.id.tvItemName);
convertView.setTag(holderGroup);
} else {
holderGroup = (ViewHolderGroup) convertView.getTag();
}
holderGroup.lblSubCategoryName.setText(parentItem.getSubCategoryName());
return convertView;
}
#Override
public View getChildView(int groupPosition,int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
//final CategoryParentItemList parentItem = (CategoryParentItemList) listParent.get(groupPosition);
//final CategoryChildListItem childItem = (CategoryChildListItem) parentItem.getChildList().get(childPosition);
CategoryChildListItem childItem = (CategoryChildListItem) getChild(groupPosition, childPosition);
ViewHolderChild holder;
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.child_row, null);
holder = new ViewHolderChild();
holder.lblItemName = (TextView) convertView.findViewById(R.id.tvSubItemName);
holder.lblDefualtPrice = (TextView) convertView.findViewById(R.id.tvrRupees);
holder.lblQty = (TextView) convertView.findViewById(R.id.tvQty);
holder.imgPlus = (ImageButton) convertView.findViewById(R.id.imageButtonPlus);
holder.imgMinus = (ImageButton) convertView.findViewById(R.id.imageButtonMinus);
convertView.setTag(holder);
} else {
holder = (ViewHolderChild) convertView.getTag();
}
holder.lblItemName.setText(childItem.getSubItemName());
holder.lblDefualtPrice.setText(childItem.getDefaultPrice());
int tmpCount = Integer.parseInt(holder.lblQty.getText().toString());
holder.imgPlus.setOnClickListener(new ClickUpdateListener(childItem,holder, tmpCount));
holder.imgMinus.setOnClickListener(new ClickUpdateListener(childItem,holder, tmpCount));
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
#Override
public boolean areAllItemsEnabled() {
return true;
}
public static int getTotalCounter() {
return totalCounter;
}
private class ClickUpdateListener implements View.OnClickListener {
ViewHolderChild holder;
public CategoryChildListItem childItem;
int counter = 0;
String counterMin;
public ClickUpdateListener(CategoryChildListItem childItem,ViewHolderChild holder, int cnt) {
this.childItem = childItem;
this.holder = holder;
this.counter = cnt;
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.imageButtonPlus) {
counter = counter + 1;
totalCounter+=1;
System.out.println(childItem.getSubItemName()+" : "+childItem.getDefaultPrice() + ": C+ :" + counter);
holder.lblQty.setText(String.format("%d", counter));
notifyDataSetChanged();
}
if(v.getId() == R.id.imageButtonMinus){
counterMin = (String) holder.lblQty.getText();
counter = Integer.parseInt(counterMin.toString().trim());
counterMin = null;
if(counter > 0) {
counter = counter - 1;
totalCounter-=1;
System.out.println(childItem.getSubItemName()+" : "+childItem.getDefaultPrice() + ": C- :" + counter);
holder.lblQty.setText(String.format("%d", counter));
notifyDataSetChanged();
}else{
Toast.makeText(context,"Qty Zero",Toast.LENGTH_SHORT).show();
}
}
}
}
}
I have this fragment class that is showed when an element is selected in a navigation drawer:
public class RecibidosFragment extends Fragment {
public ExpandListAdapterMensaje ExpAdapter;
public ArrayList<ChildMensaje> ListChild=null;
public ArrayList<Mensaje> ListMensajes=null;
public ExpandableListView ExpandList;
public ProgressDialog dialog;
public ArrayList<ArrayList<ChildMensaje>> ListChildXXXXXXXXX = null;
TextView tv;
Context mContext;
/**
* Returns a new instance of this fragment for the given section number.
*/
public static RecibidosFragment newInstance() {
RecibidosFragment fragment = new RecibidosFragment();
return fragment;
}
public RecibidosFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_recibidos, container,
false);
mContext = container.getContext();
tv = (TextView)rootView.findViewById(R.id.textView);
tv.setText(cargartodo());
ExpandList=(ExpandableListView)rootView.findViewById(R.id.expandableListView2);
ListMensajes = new ArrayList<Mensaje>();
ListChild = new ArrayList<ChildMensaje>();
ListChildXXXXXXXXX = new ArrayList<ArrayList<ChildMensaje>>();
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((menu_mensajes) activity).onSectionAttached(1);
}
public String cargartodo(){
String arreglo = loadJSONFromFile();
arreglo = "[" + arreglo+ "]";
Mensaje men =null;
ChildMensaje chmen=null;
try {
ArrayList<Mensaje> list = new ArrayList<Mensaje>();
ArrayList<ChildMensaje> ch_list;
JSONArray jsonArray = new JSONArray(arreglo);
JSONObject jsonObject2 = jsonArray.getJSONObject(0);
if(jsonObject2.optString("success").equals("0")){
arreglo="No tiene mensajes recibidos.";
}else {
for (int i = 0; i < jsonArray.length(); i++) {
arreglo="inside5";
JSONObject jsonObject = jsonArray.getJSONObject(i);
men = new Mensaje(jsonObject.optString("asunto"), jsonObject.optString("origen"), jsonObject.optString("fecha"));
ListMensajes.add(men);
chmen = new ChildMensaje(jsonObject.optString("mensaje"));
ListChild.add(chmen);
ListChildXXXXXXXXX.add(ListChild);
ExpAdapter = new ExpandListAdapterMensaje(mContext, ListMensajes, ListChildXXXXXXXXX);
ExpandList.setAdapter(ExpAdapter);
}}
} catch (JSONException e) {
e.printStackTrace();
}
return arreglo;
}
public String loadJSONFromFile() {
String json = null;
try {
//
FileInputStream is = mContext.openFileInput("mensajes.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
}
With :
public class ChildMensaje {
public String mensaje;
public ChildMensaje(){}
public ChildMensaje(String mensaje){
this.mensaje=mensaje;
}
public String getMensaje() {
return mensaje;
}
public void setMensaje(String mensaje) {
this.mensaje = mensaje;
}
}
public class ExpandListAdapterMensaje extends BaseExpandableListAdapter {
public Context context;
public ArrayList<Mensaje> noticiasArrayList;
public ArrayList<ArrayList<ChildMensaje>> ListChild;
public ExpandListAdapterMensaje(Context context, ArrayList<Mensaje> noticiasArrayList,ArrayList<ArrayList<ChildMensaje>> ListChild) {
this.context = context;
this.noticiasArrayList = noticiasArrayList;
this.ListChild=ListChild;
}
#Override
public ChildMensaje getChild(int groupPosition, int childPosition) {
return ListChild.get(groupPosition).get(childPosition);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
ChildMensaje child = getChild(groupPosition, childPosition);
ViewHolder holder=null;
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) context
.getSystemService(context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.child_row, null);
holder=new ViewHolder();
holder.mensaje=(TextView)convertView.findViewById(R.id.mensaje);
convertView.setTag(holder);
}
else {
holder=(ViewHolder)convertView.getTag();
}
holder.mensaje.setText(child.getMensaje());
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
return ListChild.get(groupPosition).size();
}
#Override
public Mensaje getGroup(int groupPosition) {
return noticiasArrayList.get(groupPosition);
}
#Override
public int getGroupCount() {
return noticiasArrayList.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
Mensaje not = (Mensaje) getGroup(groupPosition);
ViewHolder holder= null;
if (convertView == null) {
LayoutInflater inf = (LayoutInflater) context
.getSystemService(context.LAYOUT_INFLATER_SERVICE);
convertView = inf.inflate(R.layout.list_row, null);
holder=new ViewHolder();
holder.asunto=(TextView)convertView.findViewById(R.id.titulo);
holder.fecha=(TextView)convertView.findViewById(R.id.fecha);
holder.origen=(TextView)convertView.findViewById(R.id.dirigido);
convertView.setTag(holder);
}
else{
holder=(ViewHolder)convertView.getTag();
}
holder.asunto.setText(not.getAsunto());
holder.fecha.setText(not.getFecha());
holder.origen.setText(not.getOrigen());
return convertView;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public boolean areAllItemsEnabled()
{
return true;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
static class ViewHolder{
TextView asunto, fecha,origen, mensaje;
}
}
public class Mensaje {
public String origen;
public String asunto;
public String getFecha() {
return fecha;
}
public void setFecha(String fecha) {
this.fecha = fecha;
}
public String getOrigen() {
return origen;
}
public void setOrigen(String origen) {
this.origen = origen;
}
String fecha;
ArrayList<ChildMensaje> Items;
public Mensaje() {
}
public Mensaje(String asunto, String origen, String fecha) {
this.asunto = asunto;
this.fecha = fecha;
this.origen = origen;
}
public String getAsunto() {
return asunto;
}
public void setAsunto(String asunto) {
this.asunto = asunto;
}
public ArrayList<ChildMensaje> getItems() {
return Items;
}
public void setItems(ArrayList<ChildMensaje> Items) {
this.Items = Items;
}
}
My issue just appear when I'm running the app. Just in the moment that I clicked the button for go to this fragment a message appear, The aplication must to be stopped and crashed. I was just commenting the code line per line and I just know that the code is executed until that line ->
ListMensajes.add(men);
So, what I'm doing wrong ?? It has some solution ??
Thanks ;)
Ray's comment is right. It seems that the error occurs in your onCreateView() method.
tv.setText(cargartodo());
...
ListMensajes = new ArrayList<Mensaje>();
cargartodo() was called before the ListMensajes was initialized. In the cargartodo() method, ListMensajes.add() will throw a NullPointerException.
Change public ArrayList<Mensaje> ListMensajes=null to public ArrayList<Mensaje> ListMensajes= new ArrayList<Mensaje> , it may work.