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;
}
}
Related
I am a newbie in android app development and I am following this tutorial to create an image gallery.
https://deepshikhapuri.wordpress.com/2017/03/20/get-all-images-from-gallery-in-android-programmatically/.
It's working perfectly but now I want to display images in ViewPager for being able to display images by swiping left/right.I am using an adapter for doing it.
I have tried doing it but its not working I dont know why.I am not able to swipe images. Can anyone help me with it ? Am i using correct path for the images?
This project is available on github here :
https://github.com/avi003/MyApp0-master-master
ImageGallery.java:
public class ImageGallery extends AppCompatActivity {
public static ArrayList<Model_images> al_images = new ArrayList<>();
boolean boolean_folder;
Adapter_PhotosFolder obj_adapter;
GridView gv_folder;
private static final int REQUEST_PERMISSIONS = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_gallery);
gv_folder = (GridView)findViewById(R.id.gv_folder);
gv_folder.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(), PhotosActivity.class);
intent.putExtra("value",i);
startActivity(intent);
}
});
if ((ContextCompat.checkSelfPermission(getApplicationContext(),
Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) && (ContextCompat.checkSelfPermission(getApplicationContext(),
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
if ((ActivityCompat.shouldShowRequestPermissionRationale(ImageGallery.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)) && (ActivityCompat.shouldShowRequestPermissionRationale( ImageGallery.this,
Manifest.permission.READ_EXTERNAL_STORAGE))) {
} else {
ActivityCompat.requestPermissions( ImageGallery.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSIONS);
}
}else {
Log.e("Else","Else");
fn_imagespath();
}
}
public ArrayList<Model_images> fn_imagespath() {
al_images.clear();
int int_position = 0;
Uri uri;
Cursor cursor;
int column_index_data, column_index_folder_name;
String absolutePathOfImage;
uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.MediaColumns.DATA, MediaStore.Images.Media.BUCKET_DISPLAY_NAME};
final String orderBy = MediaStore.Images.Media.DATE_TAKEN;
cursor = getApplicationContext().getContentResolver().query(uri, projection, null, null, orderBy + " DESC");
column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
column_index_folder_name = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
while (cursor.moveToNext()) {
absolutePathOfImage = cursor.getString(column_index_data);
Log.e("Column", absolutePathOfImage);
Log.e("Folder", cursor.getString(column_index_folder_name));
for (int i = 0; i < al_images.size(); i++) {
if (al_images.get(i).getStr_folder().equals(cursor.getString(column_index_folder_name))) {
boolean_folder = true;
int_position = i;
break;
} else {
boolean_folder = false;
}
}
if (boolean_folder) {
ArrayList<String> al_path = new ArrayList<>();
al_path.addAll(al_images.get(int_position).getAl_imagepath());
al_path.add(absolutePathOfImage);
al_images.get(int_position).setAl_imagepath(al_path);
} else {
ArrayList<String> al_path = new ArrayList<>();
al_path.add(absolutePathOfImage);
Model_images obj_model = new Model_images();
obj_model.setStr_folder(cursor.getString(column_index_folder_name));
obj_model.setAl_imagepath(al_path);
al_images.add(obj_model);
}
}
for (int i = 0; i < al_images.size(); i++) {
Log.e("FOLDER", al_images.get(i).getStr_folder());
for (int j = 0; j < al_images.get(i).getAl_imagepath().size(); j++) {
Log.e("FILE", al_images.get(i).getAl_imagepath().get(j));
}
}
obj_adapter = new Adapter_PhotosFolder(getApplicationContext(),al_images);
gv_folder.setAdapter(obj_adapter);
return al_images;
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_PERMISSIONS: {
for (int i = 0; i < grantResults.length; i++) {
if (grantResults.length > 0 && grantResults[i] == PackageManager.PERMISSION_GRANTED) {
fn_imagespath();
} else {
Toast.makeText(ImageGallery.this, "The app was not allowed to read or write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
}
}
}
}
}
}
PhotosActivity.java:
public class PhotosActivity extends AppCompatActivity {
int int_position;
private GridView gridView;
GridViewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_gallery);
gridView = (GridView)findViewById(R.id.gv_folder);
int_position = getIntent().getIntExtra("value", 0);
adapter = new GridViewAdapter(this, al_images,int_position);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String abc = "file://" + al_images.get(int_position).getAl_imagepath().get(position);
Intent i = new Intent(getApplicationContext(), FullImageActivity.class);
i.putExtra("id", position);
i.putExtra("abc",abc);
startActivity(i);
}
});
}
}
GridViewAdapter.java:
public class GridViewAdapter extends ArrayAdapter<Model_images> {
Context context;
ViewHolder viewHolder;
ArrayList<Model_images> al_menu = new ArrayList<>();
int int_position;
public GridViewAdapter(Context context, ArrayList<Model_images> al_menu,int int_position) {
super(context, R.layout.activity_adapter__photos_folder, al_menu);
this.al_menu = al_menu;
this.context = context;
this.int_position = int_position;
}
#Override
public int getCount() {
Log.e("ADAPTER LIST SIZE", al_menu.get(int_position).getAl_imagepath().size() + "");
return al_menu.get(int_position).getAl_imagepath().size();
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getViewTypeCount() {
if (al_menu.get(int_position).getAl_imagepath().size() > 0) {
return al_menu.get(int_position).getAl_imagepath().size();
} else {
return 1;
}
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = LayoutInflater.from(getContext()).inflate(R.layout.activity_adapter__photos_folder, parent, false);
viewHolder.tv_foldern = (TextView) convertView.findViewById(R.id.tv_folder);
viewHolder.tv_foldersize = (TextView) convertView.findViewById(R.id.tv_folder2);
viewHolder.iv_image = (ImageView) convertView.findViewById(R.id.iv_image);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.tv_foldern.setVisibility(View.GONE);
viewHolder.tv_foldersize.setVisibility(View.GONE);
Glide.with(context).load("file://" + al_menu.get(int_position).getAl_imagepath().get(position))
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into(viewHolder.iv_image);
return convertView;
}
private static class ViewHolder {
TextView tv_foldern, tv_foldersize;
ImageView iv_image;
}
}
Adapter_PhotosFolder.java:
public class Adapter_PhotosFolder extends ArrayAdapter<Model_images> {
Context context;
ViewHolder viewHolder;
ArrayList<Model_images> al_menu = new ArrayList<>();
public Adapter_PhotosFolder(Context context, ArrayList<Model_images> al_menu) {
super(context, R.layout.activity_adapter__photos_folder, al_menu);
this.al_menu = al_menu;
this.context = context;
}
#Override
public int getCount() {
Log.e("ADAPTER LIST SIZE", al_menu.size() + "");
return al_menu.size();
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getViewTypeCount() {
if (al_menu.size() > 0) {
return al_menu.size();
} else {
return 1;
}
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = LayoutInflater.from(getContext()).inflate(R.layout.activity_adapter__photos_folder, parent, false);
viewHolder.tv_foldern = (TextView) convertView.findViewById(R.id.tv_folder);
viewHolder.tv_foldersize = (TextView) convertView.findViewById(R.id.tv_folder2);
viewHolder.iv_image = (ImageView) convertView.findViewById(R.id.iv_image);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.tv_foldern.setText(al_menu.get(position).getStr_folder());
viewHolder.tv_foldersize.setText(al_menu.get(position).getAl_imagepath().size()+"");
Glide.with(context).load("file://" + al_menu.get(position).getAl_imagepath().get(0))
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into(viewHolder.iv_image);
return convertView;
}
private static class ViewHolder {
TextView tv_foldern, tv_foldersize;
ImageView iv_image;
}
}
Model_images.java:
public class Model_images {
String str_folder;
ArrayList<String> al_imagepath;
public String getStr_folder() {
return str_folder;
}
public void setStr_folder(String str_folder) {
this.str_folder = str_folder;
}
public ArrayList<String> getAl_imagepath() {
return al_imagepath;
}
public void setAl_imagepath(ArrayList<String> al_imagepath) {
this.al_imagepath = al_imagepath;
}
}
FullImageActivity.java:
public class FullImageActivity extends AppCompatActivity {
ImageView images;
int position;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_full_image);
Intent i = getIntent();
images = (ImageView) findViewById(R.id.fullImage);
// Selected image id
position = i.getExtras().getInt("id");
Bundle extras = getIntent().getExtras();
String value = extras.getString("abc");
Glide.with(FullImageActivity.this)
.load(value)
.skipMemoryCache(false)
.into(images);
ViewPager mViewPager = (ViewPager) findViewById(R.id.viewpager);
mViewPager.setAdapter(new TouchImageAdapter(this,al_images));
}
}
activity_full_image.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/jazzy_pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/fullImage"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:scaleType="centerCrop"
/>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
TouchImageAdapter.java:
class TouchImageAdapter extends PagerAdapter {
Context context;
String filename;
ArrayList<Model_images> al_menu = new ArrayList<>();
int position,int_position;
public TouchImageAdapter(Context context,ArrayList<Model_images> al_menu){
this.al_menu = al_menu;
this.context = context;
}
#Override
public int getCount() {
return al_menu.size();
}
#Override
public View instantiateItem(ViewGroup container, int position) {
ImageView img = new ImageView(container.getContext());
img.setImageDrawable(getImageFromSdCard(filename,position));
container.addView(img, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
return img;
}
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
public Drawable getImageFromSdCard(String imageName,int position) {
Drawable d = null;
try {
String path = al_menu.get(int_position).getAl_imagepath().get(position)
+ "/";
Bitmap bitmap = BitmapFactory.decodeFile(path + "/" + imageName
+ ".jpeg");
d = new BitmapDrawable(context.getResources(),bitmap);
} catch (IllegalArgumentException e) {
// TODO: handle exception
}
return d;
}
}
Here you are not passing count of images inside that folder, So in TouchImageAdapter you have passing the count of folder like :
al_menu.size() // it always give you size of folder,
al_menu.get(int_position).getAl_imagepath().size();
// passing the folder position so that correct folder images are to be shown.
public TouchImageAdapter(Context context,ArrayList<Model_images> al_menu, int position){
this.al_menu = al_menu;
this.context = context;
this.int_position = position;
}
#Override
public int getCount() {
return al_menu.get(int_position).getAl_imagepath().size();
}
Here is the updated code I pushed on
https://github.com/redviper00/game
try this
String[] filenames = new String[0];
File path = new File(Environment.getExternalStorageDirectory() + "/your folder");
if (path.exists()) {
filenames = path.list();
}
for (int i = 0; i < filenames.length; i++) {
imagesPathArrayList.add(path.getPath() + "/" + filenames[i]);
Log.e("FAV_Images", imagesPathArrayList.get(i));
adapter = new ImageAdapter(FavActivity.this, imagesPathArrayList);
myviewpager.setAdapter(adapter);
}
create adapter class like this
public class ImageAdapter extends PagerAdapter {
Context context;
ArrayList<String> arrayList;
ImageAdapter(Context context, ArrayList<String> arrayList) {
this.context = context;
this.arrayList = arrayList;
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
viewPagerImageView = new ImageView(context);
viewPagerImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
Bitmap bitmap = BitmapFactory.decodeFile(arrayList.get(position));
viewPagerImageView.setImageBitmap(bitmap);
((ViewPager) container).addView(viewPagerImageView, 0);
return viewPagerImageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
It seems like you are showing Imageview above view pager
images = (ImageView) findViewById(R.id.fullImage);
that is why when you are trying to swipe imageview handle your tocuh action instead of view pager. Remove it.
I need some help. I am trying to implement the Expandable list view. My problem is that when there are more than 2 children then only group must expand if not text view and button visible on the group layout. Please go through my code and the attached Image. The textview and button are visible when there are more than 2 children also.
Screenshot of the menu
Menu.java
public class SubMenu extends BaseActivity {
String item;
ExpandableListView sec;
Toolbar carttoolbar;
private int lastExpandedPosition = -1;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sub_menu);
carttoolbar = (Toolbar) findViewById(R.id.carttoolbar);
setSupportActionBar(carttoolbar);
assert getSupportActionBar() != null;
final Drawable upArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
upArrow.setColorFilter(getResources().getColor(R.color.white), PorterDuff.Mode.SRC_ATOP);
getSupportActionBar().setHomeAsUpIndicator(upArrow);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
String catname = getIntent().getStringExtra("CatName");
getSupportActionBar().setTitle(catname);
sec = (ExpandableListView) findViewById(R.id.seondlst);
sec.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
if (lastExpandedPosition != -1
&& groupPosition != lastExpandedPosition) {
sec.collapseGroup(lastExpandedPosition);
}
lastExpandedPosition = groupPosition;
}
});
Intent hello = getIntent();
item = hello.getStringExtra("Catergory");
loaditems();
}
private void loaditems() {
String url = Constant.commonurlyell + "data_standard_item_ind_new.php?rname=standardtakeaway&id=" + item;
Log.d("ITems", url);
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading...");
progressDialog.show();
JsonObjectRequest arrayRequest = new JsonObjectRequest(Request.Method.GET, url, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
ArrayList<Subitem_base> list = new ArrayList<Subitem_base>();
ArrayList<Subitem_base_child> ch_list = new ArrayList<Subitem_base_child>();
try {
JSONArray itemsarray = response.getJSONArray("items");
Map<Integer, ArrayList<Subitem_base_child>> ch_lists = new HashMap<Integer, ArrayList<Subitem_base_child>>();
for (int i = 0; i < itemsarray.length(); i++) {
ch_list = new ArrayList<Subitem_base_child>();
JSONObject itemsobj = itemsarray.getJSONObject(i);
Subitem_base subitem = new Subitem_base();
subitem.setGroupitemname(itemsobj.getString("BaseName"));
JSONArray subitemsarray=itemsobj.getJSONArray("subitems");
for (int j = 0; j <subitemsarray.length() ; j++) {
JSONObject subitemsobj=subitemsarray.getJSONObject(j);
Subitem_base_child subitembase=new Subitem_base_child();
subitembase.setChilditemname(subitemsobj.getString("SubItemdesc"));
String pricevalue = "£";
subitembase.setChilditemprice(pricevalue.concat(subitemsobj.getString("SubItemprice")));
ch_list.add(subitembase);
}
ch_lists.put(i, ch_list);
subitem.setItems(ch_lists.get(i));
list.add(subitem);
}
SubItem_ExpandAdapter subexpand = new SubItem_ExpandAdapter(getApplicationContext(), list,SubMenu.this);
int childCount=sec.getChildCount();
Log.d("Std", String.valueOf(childCount));
sec.setAdapter(subexpand);
subexpand.notifyDataSetChanged();
progressDialog.hide();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("SecondleveError", String.valueOf(error));
}
});
arrayRequest.setRetryPolicy(new DefaultRetryPolicy(50000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(arrayRequest);
}
}
MenuAdapter.java
public class SubItem_ExpandAdapter extends BaseExpandableListAdapter {
Context subcontext;
private ArrayList<Subitem_base> subitem_bases;
private SharedPreferences loginPreferences;
private SharedPreferences.Editor loginPrefsEditor;
String itembasename, itemde, subtmsub, subitempri;
private Activity parentActivity;
public SubItem_ExpandAdapter(Context subcontext, ArrayList<Subitem_base> subitem_bases, Activity parentactivity) {
this.subcontext = subcontext;
this.subitem_bases = subitem_bases;
this.parentActivity=parentactivity;
}
static class Groupname {
private TextView group_name;
private TextView groupitem_price;
private Button grouporder;
private ImageView droparrow;
}
static class Childnames {
private TextView item_name;
private TextView item_price;
private Button order;
}
#Override
public int getGroupCount() {
return subitem_bases.size();
}
#Override
public int getChildrenCount(int groupPosition) {
ArrayList<Subitem_base_child> subitem_base_children = subitem_bases.get(groupPosition).getItems();
return subitem_base_children.size();
}
#Override
public Object getGroup(int groupPosition) {
return subitem_bases.get(groupPosition);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
ArrayList<Subitem_base_child> subitem_base_children = subitem_bases.get(groupPosition).getItems();
return subitem_base_children.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 true;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
Groupname groupname;
if (convertView == null) {
convertView = LayoutInflater.from(subcontext).inflate(R.layout.group_item, parent, false);
groupname = new Groupname();
groupname.group_name = (TextView) convertView.findViewById(R.id.group_name);
groupname.groupitem_price = (TextView) convertView.findViewById(R.id.groupitem_price);
groupname.grouporder = (Button) convertView.findViewById(R.id.grouporder);
groupname.droparrow = (ImageView) convertView.findViewById(R.id.droparrow);
convertView.setTag(groupname);
} else {
groupname = (Groupname) convertView.getTag();
}
Subitem_base groupitem = subitem_bases.get(groupPosition);
groupname.group_name.setText(groupitem.getGroupitemname());
if (isExpanded){
String[] elements = {groupitem.getGroupitemname() };
for (String s: elements) {
itembasename=s;
}
}
if (getChildrenCount(groupPosition)>=2) {
Log.d("Std", "called");
}else {
groupname.groupitem_price.setVisibility(View.VISIBLE);
groupname.droparrow.setVisibility(View.GONE);
groupname.grouporder.setVisibility(View.VISIBLE);
}
return convertView;
}
#Override
public View getChildView(final int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
final Childnames childname;
if (convertView == null) {
convertView = LayoutInflater.from(subcontext).inflate(R.layout.child_item, parent, false);
childname = new Childnames();
childname.item_name = (TextView) convertView.findViewById(R.id.item_name);
childname.item_price = (TextView) convertView.findViewById(R.id.item_price);
childname.order = (Button) convertView.findViewById(R.id.order);
convertView.setTag(childname);
}else {
childname= (Childnames) convertView.getTag();
}
Subitem_base_child childitem = (Subitem_base_child) getChild(groupPosition, childPosition);
if (childitem.getChilditemname().isEmpty()){
childname.item_name.setVisibility(View.GONE);
}else {
childname.item_name.setText(childitem.getChilditemname());
}
childname.item_price.setText(childitem.getChilditemprice());
loginPreferences = subcontext.getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
final String status = loginPreferences.getString("Status", "");
if (status.equals("0")) {
childname.order.setBackgroundResource(R.drawable.cart_disable);
}else {
childname.order.setBackgroundResource(R.drawable.cart_button);
}
childname.order.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (status.equals("0")) {
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(parentActivity);
SharedPreferences customerid = subcontext.getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
String opentimes = customerid.getString("open", "");
alertDialogBuilder.setMessage(opentimes);
alertDialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
alertDialogBuilder.setCancelable(true);
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
} else {
String poundre = childname.item_price.getText().toString();
subtmsub=childname.item_name.getText().toString();
subitempri = poundre.replace("£", "");
addcart();
}
}
});
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
private void addcart(){
loginPreferences = subcontext.getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
loginPrefsEditor = loginPreferences.edit();
SharedPreferences customerid = subcontext.getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
loginPreferences.edit();
String customid = customerid.getString("customerid", "");
String cartdetails = itembasename + " " + subtmsub;
String cartspacong = cartdetails.replace(" ", "$");
cartspacong = cartspacong.replace("&", "and");
String addcarturl = Constant.commonurltake + "cart_process.php?userid=" + customid + "&Item=" + cartspacong + "&Itemcount=1&price=" + subitempri + "&page=items";
Log.d("Cart", addcarturl);
JsonArrayRequest cartreq = new JsonArrayRequest(Request.Method.POST, addcarturl, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject cartobj = response.getJSONObject(i);
String cartnumber = cartobj.getString("count");
loginPrefsEditor.putString("Count", cartnumber);
BaseActivity.cartnumber.setVisibility(View.VISIBLE);
BaseActivity.cartnumber.setText(cartnumber);
loginPrefsEditor.apply();
if (cartobj.has("message")) {
Toast carttost = Toast.makeText(subcontext, cartobj.getString("message"), Toast.LENGTH_SHORT);
carttost.setGravity(Gravity.CENTER, 0, 0);
carttost.show();
} else {
Toast carttost = Toast.makeText(subcontext, "Product Added To Cart", Toast.LENGTH_SHORT);
carttost.setGravity(Gravity.CENTER, 0, 0);
carttost.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(subcontext, "" + error, Toast.LENGTH_SHORT).show();
}
});
cartreq.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(cartreq);
}
}
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);
}
I am calling three JSONRequests with Volley and this method is called at every response of the request. This method only is executed when all three responses are ready. But when I try to update the expandable list it fails to display on the screen. Could anyone see if I am doing something wrong?
private void updateWhenReady(){
System.out.println(validCurrent+ " " + validDaily + " " + validHourly );
if(validCurrent && validDaily && validHourly)
{
System.out.println("in");
for (WeatherCondition wc: dailyResponseList)
{
ArrayList<WeatherCondition> tempList = new ArrayList<>();
for(WeatherCondition w: hourlyResponseList)
{
if(w.getDate().equalsIgnoreCase(wc.getDate()))
{
tempList.add(w);
}
}
weatherList.put(wc,tempList);
}
for (WeatherCondition weatherCondition: weatherList.keySet())
{
System.out.println(" + " + weatherCondition.getDate());
}
weatherList = dbHelper.getWeatherConditionsHashMap();
hourlyList = new ArrayList<WeatherCondition>(weatherList.keySet());
adapter = new WeatherSearchListAdapter(getActivity().getApplicationContext(), weatherList, hourlyList);
expList.setAdapter(adapter);
adapter.notifyDataSetChanged();
System.out.println(validCurrent + " " + validDaily + " " + validHourly);
validCurrent = false;
validDaily = false;
validHourly = false;
}
}
and the following is the explist adapter
public class WeatherSearchListAdapter extends BaseExpandableListAdapter {
private Context ctx;
private HashMap<WeatherCondition, List<WeatherCondition>> weatherList;
private List<WeatherCondition> list;
public WeatherSearchListAdapter(Context ctx, HashMap<WeatherCondition, List<WeatherCondition>> parentList, List<WeatherCondition> list){
this.weatherList = parentList;
this.list = list;
this.ctx = ctx;
};
#Override
public int getGroupCount() {
return list.size();
}
#Override
public int getChildrenCount(int groupPosition) {
return weatherList.get(list.get(groupPosition)).size();
}
#Override
public Object getGroup(int groupPosition) {
return list.get(groupPosition);
}
#Override
public Object getChild(int parent, int child) {
return weatherList.get(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) {
WeatherCondition groupWeatherCondition = (WeatherCondition) getGroup(groupPosition);
if(convertView == null)
{
LayoutInflater inflator = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflator.inflate(R.layout.fragment_daily_list_parent, parent, false);
}
ImageView weatherIconIdIV = (ImageView) convertView.findViewById(R.id.weatherIconIV);
ImageView windIconIdIV = (ImageView) convertView.findViewById(R.id.windDirectionIV);
TextView humidityTV = (TextView) convertView.findViewById(R.id.humitityListText);
TextView rainTV = (TextView) convertView.findViewById(R.id.rainListText);
TextView windDirectionTV = (TextView) convertView.findViewById(R.id.windDirectionText);
TextView windSpeedTV = (TextView) convertView.findViewById(R.id.windSpeedText);
TextView maxTempTV = (TextView) convertView.findViewById(R.id.maxTempListText);
TextView minTempTV = (TextView) convertView.findViewById(R.id.minTempListText);
TextView dateTV = (TextView) convertView.findViewById(R.id.dateListText);
String name = groupWeatherCondition.getWeatherIconId();
int weatherIconId = ctx.getResources().getIdentifier(name, "drawable", ctx.getPackageName());
weatherIconIdIV.setImageResource(weatherIconId);
String name1 = groupWeatherCondition.getWind().getWindIconId();
int windIconId = ctx.getResources().getIdentifier(name1, "drawable", ctx.getPackageName());
windIconIdIV.setImageResource(windIconId);
humidityTV.setText(groupWeatherCondition.getHumidity());
rainTV.setText(groupWeatherCondition.getRain());
windDirectionTV.setText(groupWeatherCondition.getWind().getWindDirection());
windSpeedTV.setText(groupWeatherCondition.getWind().getSpeed());
maxTempTV.setText(groupWeatherCondition.getMaxTemp());
minTempTV.setText(groupWeatherCondition.getMinTemp());
dateTV.setText(groupWeatherCondition.getDate());
convertView.setBackgroundColor(Color.parseColor("#5E5E5E"));
return convertView;
}
#Override
public View getChildView(int parent, int child, boolean isLastChild, View convertView, ViewGroup parentView) {
WeatherCondition childWeatherCondition = (WeatherCondition) getChild(parent, child);
if(convertView == null)
{
LayoutInflater inflator = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflator.inflate(R.layout.fragment_daily_list_parent, parentView, false);
}
ImageView weatherIconIdIV = (ImageView) convertView.findViewById(R.id.weatherIconIV);
ImageView windIconIdIV = (ImageView) convertView.findViewById(R.id.windDirectionIV);
TextView humidityTV = (TextView) convertView.findViewById(R.id.humitityListText);
TextView rainTV = (TextView) convertView.findViewById(R.id.rainListText);
TextView windDirectionTV = (TextView) convertView.findViewById(R.id.windDirectionText);
TextView windSpeedTV = (TextView) convertView.findViewById(R.id.windSpeedText);
TextView maxTempTV = (TextView) convertView.findViewById(R.id.maxTempListText);
TextView minTempTV = (TextView) convertView.findViewById(R.id.minTempListText);
TextView dateTV = (TextView) convertView.findViewById(R.id.dateListText);
String name = childWeatherCondition.getWeatherIconId();
int weatherIconId = ctx.getResources().getIdentifier(name, "drawable", ctx.getPackageName());
weatherIconIdIV.setImageResource(weatherIconId);
String name1 = childWeatherCondition.getWind().getWindIconId();
int windIconId = ctx.getResources().getIdentifier(name1, "drawable", ctx.getPackageName());
windIconIdIV.setImageResource(windIconId);
humidityTV.setText(childWeatherCondition.getHumidity());
rainTV.setText(childWeatherCondition.getRain());
windDirectionTV.setText(childWeatherCondition.getWind().getWindDirection());
windSpeedTV.setText(childWeatherCondition.getWind().getSpeed());
maxTempTV.setText(childWeatherCondition.getMaxTemp());
minTempTV.setText(childWeatherCondition.getMinTemp());
dateTV.setText(childWeatherCondition.getDate());
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
Do the variable initializations before the logic starts -
private void updateWhenReady(){
System.out.println(validCurrent+ " " + validDaily + " " + validHourly );
weatherList = dbHelper.getWeatherConditionsHashMap();
hourlyList = new ArrayList<WeatherCondition>(weatherList.keySet());
adapter = new WeatherSearchListAdapter(getActivity().getApplicationContext(), weatherList, hourlyList);
System.out.println(validCurrent + " " + validDaily + " " + validHourly);
if(validCurrent && validDaily && validHourly)
{
System.out.println("in");
for (WeatherCondition wc: dailyResponseList)
{
ArrayList<WeatherCondition> tempList = new ArrayList<>();
for(WeatherCondition w: hourlyResponseList)
{
if(w.getDate().equalsIgnoreCase(wc.getDate()))
{
tempList.add(w);
}
}
weatherList.put(wc,tempList);
}
for (WeatherCondition weatherCondition: weatherList.keySet())
{
System.out.println(" + " + weatherCondition.getDate());
}
//Do you need to reset these? What if only two of the three were true?
validCurrent = false;
validDaily = false;
validHourly = false;
}
}
expList.setAdapter(adapter);
/* If you are setting adapter every time *updateWhenReady* is invoked, no need to notifyDataSetChanged, because its a new adapter and layout will be drawn fresh */
//adapter.notifyDataSetChanged();
}
In getChildView
inflate using fragment_daily_list_parent
copy-past error?
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();
}
}
}
}
}