add image from url to viewpager in second and third position - java

Here i have two url but when i run this app this images are been loaded to second page means first image will load in second page after few second the second image also adds to same loaction by overlapping. i need to add this to second and third pages these url
viewPager = (ViewPager) findViewById(R.id.splash);
ImageAdapter adapter = new ImageAdapter(this);
viewPager.setAdapter(adapter);
public class ImageAdapter extends PagerAdapter {
Context context;
private int[] GalImages = new int[] {
R.drawable.slider,
R.drawable.slider,
R.drawable.slider,
};
ImageAdapter(Context context){
this.context=context;
}
#Override
public int getCount() {
return GalImages.length;
// return 10;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView = new ImageView(context);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setImageResource(GalImages[position]);
new LoadImage(imageView).execute("http://www.gadgetbaazar.com/wp-content/uploads/2016/12/Top-Mobile-Phones.jpg");
new LoadImage(imageView).execute("https://pisces.bbystatic.com/BestBuy_US/store/ee/2015/com/pm/nav_desktops_1115.jpg");
container.addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
private class LoadImage extends AsyncTask<String, String, Bitmap> {
ImageView img=null;
public LoadImage(ImageView img){
this.img=img;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected Bitmap doInBackground(String... args) {
Bitmap bitmap=null;
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if(image != null){
img.setImageBitmap(image);
}
}
}
}

Try this
#Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView = new ImageView(context);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
if(position == 0){
imageView.setImageResource(GalImages[position]);
}else if(position == 1){
new LoadImage(imageView).execute("http://www.gadgetbaazar.com/wp-content/uploads/2016/12/Top-Mobile-Phones.jpg");
}else if(position ==2){
new LoadImage(imageView).execute("https://pisces.bbystatic.com/BestBuy_US/store/ee/2015/com/pm/nav_desktops_1115.jpg");
}
container.addView(imageView, 0);
return imageView;
}

Related

Android volley gridview onclick item index doesnt start with 0

I am using a custom gridview adapter to show images with volley singleton. The gridview showing the images are fine, its just that when I click the FIRST image it crashes instantly.
I have tried using URLS[i-6] but it doesnt return the right thing. There are 6 images, somehow the index of the first image is 6 thus causing the out of bound exception. I tried changing bits here and there that might cause the index starting at 6 but no result at all..
The error:
java.lang.ArrayIndexOutOfBoundsException: length=6; index=6
at com.example.user.assignmentfourtwo.MainActivity$1$1.onItemClick(MainActivity.java:80)
Which is this line:
Toast.makeText(MainActivity.this, URLS[i].toString(), Toast.LENGTH_LONG).show();
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private final int THUMBNAIL_SIZE = 250;
private final String KEY = "IMAGE";
ArrayList<Bitmap> bitmaps = new ArrayList<Bitmap>();
private static final String URLS[] = {
"http://10.0.2.2/Android%20A4_1/germany.png",
"http://10.0.2.2/Android%20A4_1/indonesia.png",
"http://10.0.2.2/Android%20A4_1/japan.png",
"http://10.0.2.2/Android%20A4_1/sarawak.png",
"http://10.0.2.2/Android%20A4_1/singapore.png",
"http://10.0.2.2/Android%20A4_1/switzerland.png",
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for(int i = 0; i<URLS.length; i++) {
LoadingImages(URLS[i]);
}
}
private void LoadingImages(String url) {
ImageLoader imageLoader = MySingleton.getInstance(getApplicationContext()).getImageLoader();
imageLoader.get(url, new ImageLoader.ImageListener() {
#Override
public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
Bitmap image = response.getBitmap();
Bitmap thumbnail = ThumbnailUtils.extractThumbnail(image, THUMBNAIL_SIZE, THUMBNAIL_SIZE);
bitmaps.add(thumbnail);
GridView gridView = (GridView)findViewById(R.id.grid_layout);
final ImageAdapter imageAdapter = new ImageAdapter(MainActivity.this, bitmaps);
gridView.setAdapter(imageAdapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(MainActivity.this, URLS[i].toString(), Toast.LENGTH_LONG).show();
// Intent intent = new Intent(getApplicationContext(), Main2Activity.class);
// intent.putExtra(KEY, URLS[i]);
// startActivity(intent);
}
});
}
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Do you even error?", error.getMessage());
}
});
}
}
MySingleton.java:
public class MySingleton {
private static MySingleton instance;
private RequestQueue requestQueue;
private ImageLoader imageLoader;
private static Context context;
private MySingleton(Context context){
this.context = context;
requestQueue = Volley.newRequestQueue(context);
imageLoader = new ImageLoader(requestQueue, new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap> cache = new LruCache<>(6);
#Override
public Bitmap getBitmap(String url) {
Bitmap bmp = cache.get(url);
if (bmp == null) {
System.out.println("Not in cache");
} else {
System.out.println("In cache");
}
return bmp;
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
System.out.println("Put in cache");
cache.put(url, bitmap);
}
});
}
public static synchronized MySingleton getInstance(Context context) {
if (instance == null) {
instance = new MySingleton(context);
}
return instance;
}
public ImageLoader getImageLoader() {
return imageLoader;
}
}
ImageAdapter.java:
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<Bitmap> bitmaps;
private final String KEY = "IMAGE";
public ImageAdapter(Context context, ArrayList<Bitmap> bitmaps) {
this.mContext = context;
this.bitmaps = bitmaps;
}
#Override
public int getCount() {
return bitmaps.size();
}
#Override
public Object getItem(int i) {
return bitmaps.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (view == null) {
final LayoutInflater layoutInflater = LayoutInflater.from(mContext);
view = layoutInflater.inflate(R.layout.griditems, null);
MyViewHolder myViewHolder = new MyViewHolder(view);
view.setTag(myViewHolder);
}
MyViewHolder myViewHolder = (MyViewHolder)view.getTag();
myViewHolder.img.setImageBitmap(bitmaps.get(i));
return view;
}
public class MyViewHolder {
public ImageView img;
public MyViewHolder(View view) {
img = view.findViewById(R.id.image1);
}
}
}

Activity not an enclosing class

public Object instantiateItem(ViewGroup container, int position) {
Context context = FullImageActivity.this; // i get error in this line that its not an enclosing class
I simply want to call FullImageActivity to ImageAdapter class
ImageAdapter class
public class ImageAdapter extends PagerAdapter {
public String mImages[] = {("http://www.fashionlady.in/wp-content/uploads/2016/03/creative-punjabi-mehndi-design-2016.jpg"),
("https://lumiere-a.akamaihd.net/v1/images/uk_toystory_chi_woody_n_5b5a006f.png?region=0,0,300,300"),
("https://lumiere-a.akamaihd.net/v1/images/open-uri20150422-20810-10n7ovy_9b42e613.jpeg"),
("http://www.wetpaint.com/wp-content/uploads/2015/11/toy-story-20th-anniversary.jpg"),
("http://i.imgur.com/4IZMjx3.jpg")};
#Override
public int getCount() {
return mImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = FullImageActivity.this;
ImageView imageView = new ImageView(context);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
Picasso.with(context).load(mImages[position]).placeholder(R.drawable.loading2).error(R.drawable.nointernet).into(imageView);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
This is my FullImageActivity class
public class FullImageActivity extends AppCompatActivity {
TouchImageView img;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("ViewPager");
setContentView(R.layout.activity_full_image);
Intent i = getIntent();
TouchImageView img = new TouchImageView(this);
int position = i.getExtras().getInt("id");
ImageAdapter adapter = new ImageAdapter();
img = (TouchImageView) findViewById(R.id.img);
img.setMaxZoom(4f);
Picasso.with(getApplicationContext()).load(adapter.mImages[position]).into(img);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(adapter);
}
Your Adapter Class
public class ImageAdapter extends PagerAdapter {
Context activity_context;
public String mImages[] = {("http://www.fashionlady.in/wp-content/uploads/2016/03/creative-punjabi-mehndi-design-2016.jpg"),
("https://lumiere-a.akamaihd.net/v1/images/uk_toystory_chi_woody_n_5b5a006f.png?region=0,0,300,300"),
("https://lumiere-a.akamaihd.net/v1/images/open-uri20150422-20810-10n7ovy_9b42e613.jpeg"),
("http://www.wetpaint.com/wp-content/uploads/2015/11/toy-story-20th-anniversary.jpg"),
("http://i.imgur.com/4IZMjx3.jpg")};
public ImageAdapter(Context context)
{
activity_context=context;
}
#Override
public int getCount() {
return mImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView = new ImageView(activity_context);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
Picasso.with(activity_context).load(mImages[position]).placeholder(R.drawable.loading2).error(R.drawable.nointernet).into(imageView);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
Your Activity class
public class FullImageActivity extends AppCompatActivity {
TouchImageView img;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("ViewPager");
setContentView(R.layout.activity_full_image);
Intent i = getIntent();
TouchImageView img = new TouchImageView(this);
int position = i.getExtras().getInt("id");
ImageAdapter adapter = new ImageAdapter(FullImageActivity.this);
img = (TouchImageView) findViewById(R.id.img);
img.setMaxZoom(4f);
Picasso.with(getApplicationContext()).load(adapter.mImages[position]).into(img);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(adapter);
}

Add dot indicator to viewpager with pageradapter

I need to add dot indicator to my code for slide show so kindly help me to add this indicator and also click listner for views in page viewer
viewPager = (ViewPager) findViewById(R.id.splash);
ImageAdapter adapter = new ImageAdapter(this);
viewPager.setAdapter(adapter);
public class ImageAdapter extends PagerAdapter {
Context context;
private int[] GalImages = new int[] {
R.drawable.slider,
R.drawable.slider,
R.drawable.slider,
};
ImageAdapter(Context context){
this.context=context;
}
#Override
public int getCount() {
return GalImages.length;
// return 10;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView = new ImageView(context);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setImageResource(GalImages[position]);
new LoadImage(imageView).execute("http://www.gadgetbaazar.com/wp-content/uploads/2016/12/Top-Mobile-Phones.jpg");
new LoadImage(imageView).execute("https://pisces.bbystatic.com/BestBuy_US/store/ee/2015/com/pm/nav_desktops_1115.jpg");
container.addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
private class LoadImage extends AsyncTask<String, String, Bitmap> {
ImageView img=null;
public LoadImage(ImageView img){
this.img=img;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected Bitmap doInBackground(String... args) {
Bitmap bitmap=null;
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if(image != null){
img.setImageBitmap(image);
}
}
}
}
Here i need the indicators if possible along with pageclick listner for this viewpager
I done this using following LIB PageIndicatorView
compile 'com.romandanylyk:pageindicatorview:0.1.1'
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:id="#+id/pager"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
<com.rd.PageIndicatorView
android:id="#+id/pageIndicatorView"
android:layout_width="wrap_content"
android:layout_centerHorizontal="true"
android:layout_above="#+id/buttons"
android:layout_marginBottom="20dp"
app:piv_animationType="swap"
app:piv_viewPager="#id/pager"
android:layout_height="wrap_content" />
Java code
mViewPager = (ViewPager) findViewById(pager);
mViewPager.setAdapter(mCustomPagerAdapter);
//dots
PageIndicatorView pageIndicatorView = (PageIndicatorView) findViewById(R.id.pageIndicatorView);
pageIndicatorView.setViewPager(mViewPager);
OUTPUT

How can I use a background task within an adapter?

I have this image adapter, that is supposed to handle updating a grid of images. The problem is that I have a BackgroundImageTask running that fetches the bitmap from a URL. The getView method returns the imageView before the Background Task can finish updating it. How Can I force the Background Task to finish before it returns the imageview?
public class ImageAdapter extends BaseAdapter {
private Context mContext;
Bitmap bitmap;
List<Post> postList;
ImageView imageView;
int pos;
public ImageAdapter(Context c, List<Post> p) {
mContext = c;
postList = p;
}
public int getCount() {
return postList.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
pos=position;
View convert = convertView;
if (convert == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(GridView.AUTO_FIT, 320));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(0, 0, 0, 0);
} else {
imageView = (ImageView) convert;
}
new BackgroundImageTask().execute();
return imageView;
}
public View SetBit(Bitmap b){
imageView.setImageBitmap(b);
return imageView;
}
class BackgroundImageTask extends AsyncTask<Void, Void, Bitmap> {
#Override
protected Bitmap doInBackground(Void... params) {
Bitmap bit1=bitmap;
try {
bit1 = BitmapFactory.decodeStream((InputStream)new URL(postList.get(pos).thumbnail).getContent());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bit1;
}
#Override
protected void onPostExecute(Bitmap bit) {
SetBit(bit);
}
}
}
Instead You can pass the ImageView Object to the background Task like
new BackgroundImageTask(imageView).execute();
and
class BackgroundImageTask extends AsyncTask<Void, Void, Bitmap> {
ImageView iv;
BackgroundImageTask(ImageView imageView){
iv = imageView;
}
#Override
protected Bitmap doInBackground(Void... params) {
Bitmap bit1=bitmap;
try {
bit1 = BitmapFactory.decodeStream((InputStream)new URL(postList.get(pos).thumbnail).getContent());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bit1;
}
#Override
protected void onPostExecute(Bitmap bit) {
iv.setImageBitmap(bit);
}
}

Android Error: type mismatch error: Cannot convert Object to Content

I am creating a simple application to share images in a grid view in Android. I have created an array but when I tried to create a gridview of those images I got an error with my code that I can't resolve.
This is my code :
public class ImageAdapter extends BaseAdapter
{
private Context context;
public ImageAdapter(Context arg2)
{
Object localObject;
this.context = localObject;
}
public int getCount()
{
return MainActivity.this.mThumbIds.length;
}
public Object getItem(int paramInt)
{
return Integer.valueOf(paramInt);
}
public long getItemId(int paramInt)
{
return paramInt;
}
public View getView(int paramInt, View paramView, ViewGroup paramViewGroup)
{
if (paramView != null)
{
MainActivity.this.imageView = ((ImageView)paramView);
}
else
{
MainActivity.this.imageView = new ImageView(this.context);
MainActivity.this.imageView.setLayoutParams(new AbsListView.LayoutParams(90, 90));
MainActivity.this.imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
MainActivity.this.imageView.setPadding(5, 5, 5, 5);
}
MainActivity.this.imageView.setImageResource(MainActivity.this.mThumbIds[paramInt].intValue());
return MainActivity.this.imageView;
}
}
}
I got the error here: Type mismatch error: Cannot convert Object to Content The error is pointing on localObject
Object localObject;
Context context;
public ImageAdapter(Context arg2)
{
this.context = arg2;
}
Instead of MainActivity.this.imageView use imageView (this is not an error)
Also use #Override where ever necessary.
Are you not using arg2?
Anyway, try to actually typecast the variable:
this.context = (Context) localObject;
You will use your Base Adapter like this and update your Grid-view like below code..
public class GridViewImageAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<String> filePaths = new ArrayList<String>();
private int imageWidth;
public GridViewImageAdapter(Activity activity,
ArrayList<String> imagePaths, int imageWidth) {
this.activity = activity;
this.filePaths = imagePaths;
this.imageWidth = imageWidth;
}
#Override
public int getCount() {
return this.filePaths.size();
}
#Override
public Object getItem(int position) {
return this.filePaths.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(activity);
} else {
imageView = (ImageView) convertView;
}
// get screen dimensions
Bitmap image = decodeFile(filePaths.get(position), imageWidth,
imageWidth);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(imageWidth,
imageWidth));
imageView.setImageBitmap(image);
return imageView;
}
public static Bitmap decodeFile(String filePath, int WIDTH, int HIGHT) {
try {
File f = new File(filePath);
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
final int REQUIRED_WIDTH = WIDTH;
final int REQUIRED_HIGHT = HIGHT;
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_WIDTH
&& o.outHeight / scale / 2 >= REQUIRED_HIGHT) {
scale *= 2;
}
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
}
set the adapter value to the GridView,Imagepaths i have stored my images in SD-card so only i give the paths to adapter...All the best
gridView = (GridView) findViewById(R.id.gridView1);
// loading all image paths from SD card
imagePaths = utils.getFilePaths();
// Gridview adapter
adapter = new GridViewImageAdapter(GridViewActivity.this, imagePaths,columnWidth);
// setting grid view adapter
gridView.setAdapter(adapter);

Categories

Resources