Display images in grid view of View pager - android

I am working on image gallery for which i have made use of ViewPager addon api. I am loading images from a specific folder in sdcard. My goal is to display only 9 images per screen in ViewPager, which i am not able to achieve. The below code is the mainactivity.
public class AndroidSwipeGalleryActivity extends Activity {
private int size;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.image_gallery);
File file = new File(Environment.getExternalStorageDirectory()+"/xxxxxxx/images");
if (file.exists()) {
size = file.listFiles().length;
System.out.println("=====File exists====Length is====="+size);
double quo = (double)size/9;
System.out.println("====Dividing by 9====" + quo);
size = (int) Math.ceil(quo);
System.out.println("===Math===== "+size);
} else {
System.out.println("======File does not exists====");
}
MyPagerAdapter adapter = new MyPagerAdapter(this);
adapter.setScrCount(size);
ViewPager myPager = (ViewPager) findViewById(R.id.viewpager);
myPager.setAdapter(adapter);
myPager.setCurrentItem(0);
}
}
The Pager Adapter and Image adapter are in the below class:
public class MyPagerAdapter extends PagerAdapter {
private TextView tv;
private GridView gv;
private int scrCount;
private int count;
public int imageCount;
private Cursor cursor;
private int columnIndex;
private Activity act;
public MyPagerAdapter(Activity act) {
this.act = act;
}
public int getCount() {
return getScrCount();
}
public Object instantiateItem(View collection, int position) {
// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Create the cursor pointing to the SDCard
String uri = MediaStore.Images.Media.DATA;
String condition = uri + " like '%/beverlyhills/images%'";
cursor = act.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, condition, null, null);
count = cursor.getCount();
System.out.println("Cursor count::::"+count);
// Get the column index of the Thumbnails Image ID
columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
LayoutInflater inflater = (LayoutInflater) collection.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int resId = 0;
for (int i = 0; i < getScrCount() ; i++) {
if (count > 9) {
if (position == i) {
int num = 0;
num = count - 9;
count = num;
imageCount = 9;
}
} else {
imageCount = count;
}
}
resId = R.layout.number_one;
View view = inflater.inflate(resId, null);
((ViewPager) collection).addView(view, 0);
tv = (TextView) collection.findViewById(R.id.swipeTitleTextView);
tv.setText("Swipe Gallery");
gv = (GridView) collection.findViewById(R.id.galleryGridView);
ImageAdapter imageAdapter = new ImageAdapter(collection.getContext(), imageCount);
gv.setAdapter(imageAdapter);
// Set up a click listener
gv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(#SuppressWarnings("rawtypes") AdapterView parent, View v, int position, long id) {
// Get the data location of the image
String[] projection = {MediaStore.Images.Media.DATA};
cursor = act.managedQuery( MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, // Which columns to return
null, // Return all rows
null,
null);
columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToPosition(position);
// Get image filename
String imagePath = cursor.getString(columnIndex);
// Use this path to do further processing, i.e. full screen display
System.out.println("=====Image Path:::::"+imagePath);
}
});
return view;
}
#Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
#Override
public Parcelable saveState() {
return null;
}
#Override
public void finishUpdate(View arg0) {
// TODO Auto-generated method stub
}
#Override
public void restoreState(Parcelable arg0, ClassLoader arg1) {
// TODO Auto-generated method stub
}
#Override
public void startUpdate(View arg0) {
// TODO Auto-generated method stub
}
public int getScrCount() {
return scrCount;
}
public void setScrCount(int scrCount) {
this.scrCount = scrCount;
}
private class ImageAdapter extends BaseAdapter {
private int count;
public ImageAdapter(Context ctx, int count) {
this.count = count;
}
#Override
public int getCount() {
return count;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView picturesView;
if (convertView == null) {
picturesView = new ImageView(act);
// Move cursor to current position
cursor.moveToPosition(position);
// Get the current value for the requested column
int imageID = cursor.getInt(columnIndex);
// Set the content of the image based on the provided URI
picturesView.setImageURI(Uri.withAppendedPath(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, "" + imageID));
picturesView.setScaleType(ImageView.ScaleType.FIT_CENTER);
picturesView.setPadding(8, 8, 8, 8);
picturesView.setLayoutParams(new GridView.LayoutParams(100, 100));
}
else {
picturesView = (ImageView)convertView;
}
return picturesView;
}
}
}
The problem is I am able to load the images and display them on screen but not able to display exactly 9 images per screen. Please go through the code, it's not complex.

i have create the other demo example of view pager to manage the page and also load images. follow the steps wise, its perfectly works..
its a Pager adapter and mDataHolder(List of images) and
Set the property of gridview android:numColumns="3"
private int size;
private int start;
private int end;
private int MATRIX = 9;
public int getCount() {
int size = 0;
if (mDataHolder != null)
modular = mDataHolder.get_Listholder().size() % MATRIX;
if (modular != 0)
size++;
return ((mDataHolder.get_Listholder().size()) / MATRIX) + size;
}
#Override
public Object instantiateItem(ViewGroup container, final int pageIndex) {
mRelativeLayoutInflater = (RelativeLayout) mMasterFragmentActivity.getLayoutInflater().inflate(R.layout.member_pager_adapter, container, false);
mGridView = (GridView) mRelativeLayoutInflater.findViewById(R.id.member_gridView_list);
Calculation of pages<
size = MATRIX;
start = pageIndex * MATRIX;
end = 0;
int temp = 0;
if ((start + MATRIX) < mDataHolder.get_Listholder().size()) {
end = start + MATRIX;
} else {
temp = mDataHolder.get_Listholder().size() - start;
end = start + temp;
size = temp;
}
... and then pass the variable to gridview adapter to set other content in pager.
mAdapterMember = new AdapterMember(mContext, start, end, size);
mGridView.setAdapter(mAdapterMember);
((ViewPager) container).addView(mRelativeLayoutInflater);
return mRelativeLayoutInflater;
}
Below Manage pages variables also use the Gridview adapter to set the postion.
when the set page content position to be like (start + position)
private class AdapterMember extends BaseAdapter {
private ViewHolder mViewHolder;
private Context mContext;
private int start;
private int end;
private int size;
private AdapterMember(Context mContext, int start, int end, int size) {
this.mContext = mContext;
this.start = start;
this.end = end;
this.size = size;
}
#Override
public int getCount() {
if (size > 0)
return size;
else
return 0;
}
#Override
public Object getItem(int position) {
if (mMemberListVO.getMember().size() > 0)
return mMemberListVO.getMember().get(position);
else
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = ((Activity) mContext).getLayoutInflater().inflate(R.layout.row_member_list, null);
mViewHolder = new ViewHolder();
mViewHolder.mImageViewMemberPhoto = (NetworkImageView) convertView .findViewById(R.id.row_member_list_imageView_person);
mViewHolder.mTextViewMemberName = (TextView) convertView .findViewById(R.id.row_member_list_textview_person_name);
mViewHolder.mTextViewMemberDesignation = (TextView) convertView .findViewById(R.id.row_member_list_textview_person_designation);
mViewHolder.mTextViewMemberAddress = (TextView) convertView .findViewById(R.id.row_member_list_textview_person_address);
mViewHolder.mTextViewMemberNotification = (TextView) convertView .findViewById(R.id.row_member_list_imageview_msg_notification);
convertView.setTag(mViewHolder);
} else {
mViewHolder = (ViewHolder) convertView.getTag();
}
mViewHolder.mTextViewMemberName.setText(mDataHolder.get_Listholder().get(start + position) .get(DBHelper.mFieldMember_First_Name)
+ getString(R.string.double_quate_with_space)
+ mDataHolder.get_Listholder(). get(start + position).get(DBHelper.mFieldMember_Last_Name));
mViewHolder.mTextViewMemberDesignation.setText(mDataHolder.get_Listholder().get(start + position)
.get(DBHelper.mFieldMember_Occupation));
mViewHolder.mTextViewMemberAddress.setText(mDataHolder.get_Listholder().get(start + position) .get(DBHelper.mFieldMember_Block_No)
+ "," + getString(R.string.double_quate_with_space)
+ mDataHolder.get_Listholder().get(start + position).get(DBHelper.mFieldMember_House_No) + ","
+ getString(R.string.double_quate_with_space)
+ mDataHolder.get_Listholder().get(start + position).get(DBHelper.mFieldMember_Home_Address) + ".");
return convertView;
}
private class ViewHolder {
private NetworkImageView mImageViewMemberPhoto;
private TextView mTextViewMemberName, mTextViewMemberDesignation, mTextViewMemberAddress,
mTextViewMemberNotification;
}
}
its perfectly Working with your requirement...
The problem is solve to load the images and display them on screen its display exactly 9 images per screen.

Related

Trying to manually add item in a ListView tied to a custom cursor adapter

I need a little help for the redaction of a class. I want to add some item in my listView, and to do that I use a custom adapter found in this forum, but modified for my use :
public class AdvertisingAdapter extends cCursorAdapter {
private static final String ADMOB_PUBLISHER_ID = "YOUR_ADMOB_ID_HERE";
private final Activity activity;
private final cCursorAdapter delegate;
Context context;
static int rec = 15;
public AdvertisingAdapter(Activity activity, cCursorAdapter delegate, Context context, Cursor cursor)
{
super(context, cursor, 0);
this.activity = activity;
this.delegate = delegate;
this.context = context;
delegate.registerDataSetObserver(new DataSetObserver()
{
#Override
public void onChanged()
{
notifyDataSetChanged();
}
#Override
public void onInvalidated()
{
notifyDataSetInvalidated();
}
});
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
if (position == 0 || position % rec == 0)
{
j = j + 1 ;
if (convertView instanceof AdView)
{
notifyDataSetChanged();
return convertView;
}
else
{
AdView adView = new AdView(context);
// Disable focus for sub-views of the AdView to avoid problems with
// trackpad navigation of the list.
for (int i = 0; i < adView.getChildCount(); i++)
{
adView.getChildAt(i).setFocusable(false);
}
adView.setFocusable(false);
// Default layout params have to be converted to ListView compatible
// params otherwise there will be a ClassCastException.
float density = activity.getResources().getDisplayMetrics().density;
int height = Math.round(AdSize.BANNER.getHeight() * density);
AbsListView.LayoutParams params
= new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT,
height);
adView.setLayoutParams(params);
AdRequest adRequest = new AdRequest.Builder().build();
adView.setAdUnitId("ca-app-pub-3940256099942544/6300978111");
adView.setAdSize(com.google.android.gms.ads.AdSize.BANNER);
adView.loadAd(adRequest);
notifyDataSetChanged();
return adView;
}
}
else
{
Log.i ("TEST AD ADAPTER", String.valueOf(j)
+ " " + String.valueOf(position)
+ " " + String.valueOf(getNbreAd())
+ " " + String.valueOf(getNbrePos(position))
+ " " + String.valueOf(getCount()));
return delegate.getView(position - getNbrePos(position), convertView, parent);
}
}
public int getNbreAd(){
int l = delegate.getCount();
return (l / rec) + 1;
}
public int getNbrePos(int position){
int k = (position/rec) + 1;
return k;
}
#Override
public int getCount()
{
return delegate.getCount() + getNbreAd();
}
#Override
public Object getItem(int i)
{
return delegate.getItem(i - 1);
}
#Override
public long getItemId(int i)
{
return delegate.getItemId(i - 1);
}
#Override
public int getViewTypeCount()
{
return delegate.getViewTypeCount() + 1;
}
#Override
public int getItemViewType(int position)
{
return position == 0 ? delegate.getViewTypeCount()
: delegate.getItemViewType(position - 1);
}
#Override
public boolean areAllItemsEnabled()
{
return false;
}
#Override
public boolean isEnabled(int position)
{
return position != 0 && delegate.isEnabled(position - 1);
}
}
My cCursorAdapter :
public class cCursorAdapter extends android.widget.CursorAdapter {
DataHelper mDBHelper;
public cCursorAdapter(Context context, Cursor cursor, int flags) {
super(context, cursor, 0);
}
// The newView method is used to inflate a new view and return it,
// you don't bind any data to the view at this point.
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.list_result2, parent, false);
}
// The bindView method is used to bind all data to a given view
// such as setting the text on a TextView.
#Override
public void bindView(View view, Context context, Cursor cursor){
// Find fields to populate in inflated template
TextView nameResult = (TextView) view.findViewById(R.id.nameResult2);
TextView ageG = (TextView) view.findViewById(R.id.ageG2);
TextView nbreJoueur = (TextView) view.findViewById(R.id.nbreJoueur2);
TextView timeResult = (TextView) view.findViewById(R.id.time2);
ImageView placeGD = (ImageView) view.findViewById(R.id.placeD2);
TextView IDR2 = (TextView) view.findViewById(R.id.IDR2);
// Extract properties from cursor
String name = cursor.getString(cursor.getColumnIndexOrThrow("name"));
String place = cursor.getString(cursor.getColumnIndexOrThrow("place"));
int ageMin = cursor.getInt(cursor.getColumnIndexOrThrow("agemin"));
int ageMax = cursor.getInt(cursor.getColumnIndexOrThrow("agemax"));
int nbreMin = cursor.getInt(cursor.getColumnIndexOrThrow("nbremin"));
int nbreMax = cursor.getInt(cursor.getColumnIndexOrThrow("nbremax"));
int time = cursor.getInt(cursor.getColumnIndexOrThrow("time"));
final int ID = cursor.getInt(cursor.getColumnIndexOrThrow("_id"));
// Populate fields with extracted properties
nameResult.setText(name);
ageG.setText(String.valueOf(ageMin) + " - " + String.valueOf(ageMax));
nbreJoueur.setText(String.valueOf(nbreMin) + " - " + String.valueOf(nbreMax));
timeResult.setText(String.valueOf(time));
IDR2.setText(String.valueOf(ID));
if (place.equals("extérieur")) {
Drawable placeD = MainActivity.mContext.getResources().getDrawable(R.drawable.ic_wb_sunny_black_24dp);
placeGD.setImageDrawable(placeD);
} else if (place.equals("intérieur")){
Drawable placeD = MainActivity.mContext.getResources().getDrawable(R.drawable.ic_event_seat_black_24dp);
placeGD.setImageDrawable(placeD);
} else if (place.equals("partout")) {
Drawable placeD = MainActivity.mContext.getResources().getDrawable(R.drawable.ic_explore_black_24dp);
placeGD.setImageDrawable(placeD);
}
//Cacher l'ID (c'est pas joli)
IDR2.setVisibility(View.INVISIBLE);
}
//Override the convert to string sequence
#Override
public CharSequence convertToString(Cursor cursor){
final int colIndex = cursor.getColumnIndexOrThrow("name");
return cursor.getString(colIndex);
}
#Override
public Cursor runQueryOnBackgroundThread(CharSequence constraint)
{
Cursor currentCursor = null;
if (getFilterQueryProvider() != null)
{
return getFilterQueryProvider().runQuery(constraint);
}
String args = "";
if (constraint != null)
{
args = constraint.toString();
}
//Initialize that shit
mDBHelper = new DataHelper(MainActivity.mContext);
currentCursor = mDBHelper.getNameCursor(args);
return currentCursor;
}
}
In a certain way, it works. But when I swipe the listView too fast, I have this error :
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.tanoshi.traveler.doctorgamesfree.cCursorAdapter.bindView(cCursorAdapter.java:57)
at android.widget.CursorAdapter.getView(CursorAdapter.java:254)
at com.tanoshi.traveler.doctorgamesfree.AdvertisingAdapter.getView(AdvertisingAdapter.java:102)
I think it is becausemy listView try to load an item in a view which is not loaded.
How can I do to fix this ?
Thank you for your time.

custom List view with lazy loading causes Index outof bound exception

public class LazyImageLoadAdapter extends BaseAdapter implements
OnClickListener {
private int mCount = 10;
// String mPositionString;
private Activity activity;
private String[] data;
private static LayoutInflater inflater = null;
public ImageLoader imageLoader;
// int mTextViewResourceId;
public LazyImageLoadAdapter(Activity a, String[] d) {
activity = a;
data = d;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// mPositionString = activity.getString(d.length) + " ";
// mTextViewResourceId = textViewResourceId;
// Create ImageLoader object to download and show image in list
// Call ImageLoader constructor to initialize FileCache
imageLoader = new ImageLoader(activity.getApplicationContext());
}
public void addMoreItems(int count) {
mCount += count;
notifyDataSetChanged();
}
public int getCount() {
return mCount;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
// #Override
// public int getViewTypeCount() {
// return 2;
// }
/********* Create a holder Class to contain inflated xml file elements *********/
public static class ViewHolder {
public TextView text;
public TextView text1;
public TextView textWide;
public ImageView image;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
ViewHolder holder;
if (convertView == null) {
/****** Inflate tabitem.xml file for each row ( Defined below ) *******/
vi = inflater.inflate(R.layout.listview_row, null);
/****** View Holder Object to contain tabitem.xml file elements ******/
holder = new ViewHolder();
holder.text = (TextView) vi.findViewById(R.id.text);
holder.text1 = (TextView) vi.findViewById(R.id.text1);
holder.image = (ImageView) vi.findViewById(R.id.image);
/************ Set holder with LayoutInflater ************/
vi.setTag(holder);
} else
holder = (ViewHolder) vi.getTag();
holder.text.setText("Company " + position);
holder.text1.setText("company description " + position);
ImageView image = holder.image;
// DisplayImage function from ImageLoader Class
imageLoader.DisplayImage(data[position], image);
/******** Set Item Click Listner for LayoutInflater for each row ***********/
vi.setOnClickListener(new OnItemClickListener(position));
return vi;
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
/********* Called when Item click in ListView ************/
private class OnItemClickListener implements OnClickListener {
private int mPosition;
OnItemClickListener(int position) {
mPosition = position;
}
#Override
public void onClick(View arg0) {
MainActivity sct = (MainActivity) activity;
sct.onItemClick(mPosition);
}
}
}
at >>> imageLoader.DisplayImage(data[position], image);
the error is
public class MainActivity extends Activity implements OnScrollListener {
ListView list;
LazyImageLoadAdapter mAdapter;
private final int AUTOLOAD_THRESHOLD = 4;
private final int MAXIMUM_ITEMS = 1052;
private View mFooterView;
private Handler mHandler;
private boolean mIsLoading = false;
private boolean mMoreDataAvailable = true;
private boolean mWasLoading = false;
private Runnable mAddItemsRunnable = new Runnable() {
#Override
public void run() {
mAdapter.addMoreItems(10);
mIsLoading = false;
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
list = (ListView) findViewById(R.id.list);
// Create custom adapter for listview
mAdapter = new LazyImageLoadAdapter(this, mStrings);
// Set adapter to listview
// Button b = (Button) findViewById(R.id.button1);
// b.setOnClickListener(listener);
mHandler = new Handler();
// mAdapter = new SimpleAdapter(MainActivity.this,
// android.R.layout.simple_list_item_1);
mFooterView = LayoutInflater.from(this).inflate(R.layout.loading_view,
null);
list.addFooterView(mFooterView, null, false);
// LIST(MADAPTER);
list.setAdapter(mAdapter);
list.setOnScrollListener(this);
}
#Override
public void onDestroy() {
// Remove adapter refference from list
list.setAdapter(null);
super.onDestroy();
}
public OnClickListener listener = new OnClickListener() {
#Override
public void onClick(View arg0) {
// Refresh cache directory downloaded images
mAdapter.imageLoader.clearCache();
mAdapter.notifyDataSetChanged();
}
};
public void onItemClick(int mPosition) {
String tempValues = mStrings[mPosition];
Toast.makeText(MainActivity.this, "Image URL : " + tempValues,
Toast.LENGTH_LONG).show();
}
// Image urls used in LazyImageLoadAdapter.java file
private String[] mStrings = {
"http://androidexample.com/media/webservice/LazyListView_images/image0.png",
"http://androidexample.com/media/webservice/LazyListView_images/image1.png",
"http://androidexample.com/media/webservice/LazyListView_images/image2.png",
"http://androidexample.com/media/webservice/LazyListView_images/image3.png",
"http://androidexample.com/media/webservice/LazyListView_images/image4.png",
"http://androidexample.com/media/webservice/LazyListView_images/image5.png",
"http://androidexample.com/media/webservice/LazyListView_images/image6.png",
"http://androidexample.com/media/webservice/LazyListView_images/image7.png",
"http://androidexample.com/media/webservice/LazyListView_images/image8.png",
"http://androidexample.com/media/webservice/LazyListView_images/image9.png",
"http://androidexample.com/media/webservice/LazyListView_images/image10.png",
"http://androidexample.com/media/webservice/LazyListView_images/image0.png",
"http://androidexample.com/media/webservice/LazyListView_images/image1.png",
"http://androidexample.com/media/webservice/LazyListView_images/image2.png",
"http://androidexample.com/media/webservice/LazyListView_images/image3.png",
"http://androidexample.com/media/webservice/LazyListView_images/image4.png",
"http://androidexample.com/media/webservice/LazyListView_images/image5.png",
"http://androidexample.com/media/webservice/LazyListView_images/image6.png",
"http://androidexample.com/media/webservice/LazyListView_images/image7.png",
"http://androidexample.com/media/webservice/LazyListView_images/image8.png",
"http://androidexample.com/media/webservice/LazyListView_images/image9.png",
"http://androidexample.com/media/webservice/LazyListView_images/image10.png",
"http://androidexample.com/media/webservice/LazyListView_images/image0.png",
"http://androidexample.com/media/webservice/LazyListView_images/image1.png",
"http://androidexample.com/media/webservice/LazyListView_images/image2.png",
"http://androidexample.com/media/webservice/LazyListView_images/image3.png",
"http://androidexample.com/media/webservice/LazyListView_images/image4.png",
"http://androidexample.com/media/webservice/LazyListView_images/image5.png",
"http://androidexample.com/media/webservice/LazyListView_images/image6.png",
"http://androidexample.com/media/webservice/LazyListView_images/image7.png",
"http://androidexample.com/media/webservice/LazyListView_images/image8.png",
"http://androidexample.com/media/webservice/LazyListView_images/image9.png",
"http://androidexample.com/media/webservice/LazyListView_images/image10.png"
};
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (!mIsLoading && mMoreDataAvailable) {
if (totalItemCount >= MAXIMUM_ITEMS) {
mMoreDataAvailable = false;
list.removeFooterView(mFooterView);
} else if (totalItemCount - AUTOLOAD_THRESHOLD <= firstVisibleItem
+ visibleItemCount) {
mIsLoading = true;
mHandler.postDelayed(mAddItemsRunnable, 1000);
}
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// Ignore
}
#Override
public void onStart() {
super.onStart();
if (mWasLoading) {
mWasLoading = false;
mIsLoading = true;
mHandler.postDelayed(mAddItemsRunnable, 1000);
}
}
#Override
public void onStop() {
super.onStop();
mHandler.removeCallbacks(mAddItemsRunnable);
mWasLoading = mIsLoading;
mIsLoading = false;
}
}
this is my MainActivity class using OnScrollListener for data showing after scrolling .
and this is exception
please help me out..
My guess is that your data array does not contain the same amount of values as your mCount variable tells the adapter. Try to fix this issue the following way:
// change your method implementation that returns mCount to this one
public int getCount() {
return data.length;
}
This is supposed to fix the ArrayIndexOutOfBoundsException that you are getting. The next step for you, I guess, would be implementation of addMoreItems method so that it would add items to your array, and not just update the counter.
Edit
If you manually update mCount, consider the following code:
public void addMoreItems(int count) {
// update the counter
mCount += count;
// if now your counter exceeds the size of the array,
// set its value to the size
if (mCount >= data.length) {
mCount = data.length;
}
notifyDataSetChanged();
}
Also, just to make sure, you should check if you are trying to access your array at the index that is the same as its size: data[mCount] may be wrong, if mCount equals to the size of your array, in that case you should use data[mCount - 1] instead.

Highlight effect while pressing item in custom ListView adapter

There's a system visual effect everytime you click a view in Android. In Lollipop it's the ripple effect. When I created a ListView and associated it to an ordinary ArrayAdapter, this effect was present. Now that I've added a custom ListView, this effect is lost.
Now, I've tried to isolate what the problem is, and since using the same list item layout with a default adapter worked nicely, I would say that the problem is on my custom adapter.
I've seen many solutions related to this case that just implemented the ripple effect calling some drawables; this is not what I'm trying to do. The ripple effect shows only because I'm running the app on Android 5, now what I want to do is to have the default system highlight effect for my items when they're being clicked.
Here are the (hopefully) related pieces of my custom adapter:
public class CustomCardSetsAdapter extends BaseAdapter {
List<Card> totalList;
ArrayList<Boolean> hiddenItems;
ListView parentLV;
Integer curPosition = -1;
public static int selectedRowIndex;
public CustomCardSetsAdapter(CardSets cardList, ListView parentListView)
{
this.parentLV = parentListView;
assignSetValues(cardList);
totalList = cardList.getBlackrockMountain();
totalList.addAll(cardList.getClassic());
totalList.addAll(cardList.getCurseofNaxxramas());
totalList.addAll(cardList.getGoblinsvsGnomes());
Collections.sort(totalList,
new Comparator<Card>() {
public int compare(Card f1, Card f2) {
return f1.toString().compareTo(f2.toString());
}
});
hiddenItems = new ArrayList<>();
for (int i = 0; i < totalList.size(); i++) {
if(!totalList.get(i).getCollectible())
hiddenItems.add(true);
else
hiddenItems.add(false);
}
}
#Override
public int getCount() {
return (totalList.size() - getHiddenCount());
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
final int index = getRealPosition(position);
if(convertView == null) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
convertView = inflater.inflate(R.layout.card_list_item, parentLV, false);
}
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer prevPosition = curPosition;
curPosition = position;
if(prevPosition >= parentLV.getFirstVisiblePosition() &&
prevPosition <= parentLV.getLastVisiblePosition())
{
View view = parentLV.getChildAt(prevPosition- parentLV.getFirstVisiblePosition());
parentLV.getAdapter().getView(prevPosition,view, parentLV);
}
v.setBackgroundColor(Color.WHITE);
}
});
Card curCard = totalList.get(index);
TextView cardName = (TextView) convertView.findViewById(R.id.cardName);
cardName.setText(curCard.getName());
setRarityColor(curCard,cardName);
TextView manaCost = (TextView) convertView.findViewById(R.id.manaCost);
manaCost.setText((curCard.getCost()).toString());
ImageView setIcon = (ImageView) convertView.findViewById(R.id.setIcon);
setSetIcon(curCard,setIcon);
if(position == curPosition)
convertView.setBackgroundColor(Color.WHITE);
else
convertView.setBackgroundColor(Color.TRANSPARENT);
return convertView;
}
#Override
public int getItemViewType(int position) {
return R.layout.card_list_item;
}
#Override
public int getViewTypeCount() {
return 1;
}
#Override
public boolean isEmpty() {
return false;
}
private int getHiddenCount()
{
int count = 0;
for(int i = 0;i <totalList.size();i++)
if(hiddenItems.get(i))
count++;
return count;
}
private int getRealPosition(int position) {
int hElements = getHiddenCountUpTo(position);
int diff = 0;
for(int i=0;i<hElements;i++) {
diff++;
if(hiddenItems.get(position+diff))
i--;
}
return (position + diff);
}
private int getHiddenCountUpTo(int location) {
int count = 0;
for(int i=0;i<=location;i++) {
if(hiddenItems.get(i))
count++;
}
return count;
}
}
Thanks in advance.
in your ListView XML, add:
android:drawSelectorOnTop="true"
I also think you are using your adapter wrong...
Use the ViewHolder Pattern on your Adapter:
public class CustomCardSetsAdapter extends BaseAdapter {
List<Card> totalList;
ArrayList<Boolean> hiddenItems;
ListView parentLV;
Integer curPosition = -1;
public static int selectedRowIndex;
private class ViewHolderRow{
TextView cardName;
TextView manaCost;
ImageView setIcon;
}
public CustomCardSetsAdapter(CardSets cardList, ListView parentListView)
{
this.parentLV = parentListView;
assignSetValues(cardList);
totalList = cardList.getBlackrockMountain();
totalList.addAll(cardList.getClassic());
totalList.addAll(cardList.getCurseofNaxxramas());
totalList.addAll(cardList.getGoblinsvsGnomes());
Collections.sort(totalList,
new Comparator<Card>() {
public int compare(Card f1, Card f2) {
return f1.toString().compareTo(f2.toString());
}
});
hiddenItems = new ArrayList<>();
for (int i = 0; i < totalList.size(); i++) {
if(!totalList.get(i).getCollectible())
hiddenItems.add(true);
else
hiddenItems.add(false);
}
}
#Override
public int getCount() {
return (totalList.size() - getHiddenCount());
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
final int index = getRealPosition(position);
ViewHolderRow theRow;
if(convertView == null) {
theRow = new ViewHolderRow();
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
convertView = inflater.inflate(R.layout.card_list_item, parentLV, false);
// Cache your views
theRow.cardName = (TextView) convertView.findViewById(R.id.cardName);
theRow.manaCost = (TextView) convertView.findViewById(R.id.manaCost);
theRow.setIcon = (ImageView) convertView.findViewById(R.id.setIcon);
// Set the Tag to the ViewHolderRow
convertView.setTag(theRow);
}else{
// get the Row to re-use
theRow = (ViewHolderRow) convertView.getTag();
}
//... Removed convertView.setOnClickListener
Card curCard = totalList.get(index);
// Set Items
theRow.cardName.setText(curCard.getName());
setRarityColor(curCard,theRow.cardName);
theRow.manaCost.setText((curCard.getCost()).toString());
setSetIcon(curCard,theRow.setIcon);
if(position == curPosition){
convertView.setBackgroundColor(Color.WHITE);
}else{
convertView.setBackgroundColor(Color.TRANSPARENT);
}
return convertView;
}
#Override
public int getItemViewType(int position) {
return R.layout.card_list_item;
}
#Override
public int getViewTypeCount() {
return 1;
}
#Override
public boolean isEmpty() {
return false;
}
private int getHiddenCount()
{
int count = 0;
for(int i = 0;i <totalList.size();i++)
if(hiddenItems.get(i))
count++;
return count;
}
private int getRealPosition(int position) {
int hElements = getHiddenCountUpTo(position);
int diff = 0;
for(int i=0;i<hElements;i++) {
diff++;
if(hiddenItems.get(position+diff))
i--;
}
return (position + diff);
}
private int getHiddenCountUpTo(int location) {
int count = 0;
for(int i=0;i<=location;i++) {
if(hiddenItems.get(i))
count++;
}
return count;
}
}
Set an onListItemClickListener instead of using this on the entire convertView...
yourListView.setOnItemClickListener(ListListener);
private final OnItemClickListener ListListener = new OnItemClickListener{
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long arg3) {
// ... Do something on click
}
}

android - How to check how many elements are present in a GridView?

I am dynamically adding images to a GridView.
I want to have a counter to check how many images are present in a GridView.
The purpose is to restrict the user to add maximum of "n" images.
Therefore I want to have a counter which will count this number and I will check accordingly.
public class ExistingDetailedActivity extends Activity {
public String images,audiopath,name,assignedTo;
TextView ringtonename,assigned;
public GridView gridView;
public String [] imgpath;
CustomBaseExistAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_existing_detailed);
Intent i = getIntent();
if(i.hasExtra("BNDL")){
Bundle bdl = getIntent().getBundleExtra("BNDL");
if(bdl.get("IMAGEPATH") != null){
images = bdl.getString("IMAGEPATH");
}
if(bdl.get("AUDIOPATH") != null){
audiopath = bdl.getString("AUDIOPATH");
}
if(bdl.get("RINGTONENAME") != null){
name = bdl.getString("RINGTONENAME");
}
if(bdl.get("ASSIGNEDTO") != null){
assignedTo = bdl.getString("ASSIGNEDTO");
}
}
Typeface FONT_NAME = Typeface.createFromAsset(this.getAssets(), "komika-title-brush-1361511399.ttf");
imgpath=images.split("\\*") ;
ringtonename=(TextView) findViewById(R.id.textView2);
ringtonename.setText(name);
ringtonename.setTypeface(null, Typeface.BOLD);
ringtonename.setTypeface(FONT_NAME);
assigned=(TextView) findViewById(R.id.textView4);
assigned.setText(assignedTo);
assigned.setTypeface(null, Typeface.BOLD);
assigned.setTypeface(FONT_NAME);
gridView=(GridView) findViewById(R.id.gridview1);
adapter = new CustomBaseExistAdapter(this,imgpath);
//adapter.notifyDataSetChanged();
gridView.invalidateViews();
gridView.setAdapter(adapter);
}
}
Another one is
public class CustomBaseExistAdapter extends BaseAdapter{
private final Activity context;
public String[] imagepath;
private String[] imagepath1=null;
private String[] imagepathBackUp=null;
public CustomBaseExistAdapter(Activity context,
String[] imagepath) {
this.context = context;
this.imagepath = imagepath;
this.imagepathBackUp =imagepath;
List<String> nonBlank = new ArrayList<String>();
for(String s: imagepath) {
if (!s.trim().isEmpty()) {
nonBlank.add(s);
}
}
imagepath1 = (String[]) nonBlank.toArray( new String[nonBlank.size()] );
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return imagepath.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public int getViewTypeCount() {
return 1;
}
#Override
public int getItemViewType(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
convertView = null;
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.custom_image_with_checkbox, null);
CheckBox cb=(CheckBox) convertView.findViewById(R.id.checkBox1);
final ImageView imageView = (ImageView) convertView.findViewById(R.id.imgThumb);
cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
int id = buttonView.getId();
if(isChecked){
/*String newList[] = new String[imagepath.length - 1];
int count = 0;
for (int i = 0; i < imagepath.length; i++) {
if (imagepath.length - 1 > 0) {
if (imagepath[i] == imagepath1[position]) { // itemPath[1] as the range starts from 0, so 1 would be ITEM2
// SKIP IF MATCHES THE ITEM YO WANT TO REMOVE
} else {
newList[count] = imagepath[i];
count++;
}
}
}
imagepath=new String[newList.length];
imagepath= newList;*/
List<String> newlist= new ArrayList<String>(Arrays.asList(imagepath));
newlist.remove(imagepath1[position]);
imagepath=null;
imagepath = newlist.toArray(new String[newlist.size()]);
/*new String[newlist.size()];
for(int j =0;j<newlist.size();j++){
imagepath[j] = newlist.get(j);
}*/
notifyDataSetChanged();
}
}
});
imageView.setImageBitmap(BitmapFactory.decodeFile(imagepath[position]));
}
return convertView;
}
}
To know number of Elements in GridView, here ,
put int count = (position + 1); in your GridView Adapter getView(..) method. It is callback method, called number of times to populate your Gridview. Starts from 0.
int count = 0; // define count as global instance var.
public View getView(final int position, View convertView, ViewGroup parent){
...
count = position + 1;
...
}
count is what you want.

how to update list item in list view in android

i have list view ,in list view i try to display images in list view after that i want change size of image and update it to list view..is it possible to update images at run-time....
and how can get current view that dispay currently and can we modify it..??
this is class....
public class GalleryAdapter extends BaseAdapter {
private Context mContext;
private int numcolumn;
private int NoOfListItem;
GridView grid;
int ListItemHeight;
private String[] header;
SharedPreferences groupbyPref;
private SharedPreferences GalleryPref;
ScreenshotLibrary myScreenshotLibrary = null;
// arrylist which contain path of images from sdcard..
ArrayList<String> itemList = new ArrayList<String>();
private TableLayout table_layout;
// layout parm of image
LinearLayout.LayoutParams parms;
public int fromback = 0;
ImageView img;
private LruCache<String, Bitmap> mMemoryCache;
private int size;
Cursor imagecursor;
int counter = 0;
// Constructor
#SuppressLint("NewApi")
public GalleryAdapter(Context gallery, int NumOfListItem, String[] str) {
}
#Override
public int getCount() {
return NoOfListItem;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return itemList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public void setnumcol(int i) {
grid.setNumColumns(i);
grid.requestLayout();
notifyDataSetChanged();
}
public int ListItemHeight(int length) {
SharedPreferences ImageSizePref = PreferenceManager
.getDefaultSharedPreferences(mContext);
if (length % numcolumn == 0) {
return ((length / numcolumn))
* ImageSizePref.getInt("ImageParm", 100) + 55;
} else {
return ((length / numcolumn) + 1)
* ImageSizePref.getInt("ImageParm", 100) + 55;
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
View customRow = inflater.inflate(R.layout.list_item, null);
// textview which display header of screenshot library
TextView txt = (TextView) customRow.findViewById(R.id.header);
txt.setText(header[position]);
// tablelayout which will be used to contain images inside that
table_layout = (TableLayout) customRow.findViewById(R.id.tableLayout);
int count = 0;
// loop for num of row in view
for (int i = 0; i < RowMaking(numcolumn); i++) {
//
TableRow row = new TableRow(mContext);
row.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
// inner loop used for number of images in each row of
// tablelayout....and num of
for (int j = 1; j <= numcolumn; j++) {
img = new ImageView(mContext);
img.setAdjustViewBounds(true);
if (count < itemList.size()) {
int resId = mContext.getResources().getIdentifier(
itemList.get(count++), "drawable",
mContext.getPackageName());
loadBitmap(resId, img);
// img.setLayoutParams(parms);
img.setLayoutParams(new LayoutParams(size, size));
Log.i("fromcache", "num" + counter);
img.getResources();
} else {
break;
}
row.addView(img);
}
table_layout.addView(row);
}
customRow.setLayoutParams(new ListView.LayoutParams(
ListView.LayoutParams.MATCH_PARENT, ListItemHeight(itemList
.size())));
return customRow;
}
yes you can update listview with dynamicdata..
just see this tutorial...
http://www.developerfusion.com/article/145373/android-listviews-with-dynamic-data/
and i reccomend you to use piccaso for images...
Use picasso which is easy to use..
In your Adapter ..
#Override
public void getView(int position, View convertView, ViewGroup parent) {
ImageView view = (ImageView) convertView.findViewById(R.id.ranking_prod_pic);
Picasso.with(context).load(url).into(view); //url is image url
//you can resize image if you want
/* Picasso.with(context) .load(url) .resize(50, 50) .centerCrop() .into(view) */
}
http://square.github.io/picasso/

Categories

Resources