Image Switcher Issue in Android - java

I am using image switcher to display several picture.
I have initialized the final Integer[] imageIDs = {} and use declare elements in it in If-Else statement which locates in the OnCreate. I do so because for each different places I would like to input different pictures into the imageIDs. In this example is "UK". So if another places was chosen, the imageIDs should have different pictures refer to.
Unfortunately there was nothing in the imageswitcher when I run the apps.
final Integer[] imageIDs = {};
private ImageSwitcher imageSwitcher;
DBAdapter dbAdapter;
final Context context = this;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.attraction_details);
Intent intent = getIntent();
String selectedSubArea = intent.getStringExtra("SelectedSubArea");
Button btnAddToTrip = (Button) findViewById(R.id.btnAddToTrip);
Button btnAddToFav = (Button) findViewById(R.id.btnAddToFav);
Button btnShowAttractionLocation = (Button) findViewById(R.id.btnShowAttractionLocation);
TextView description = (TextView) findViewById(R.id.description);
TextView address = (TextView) findViewById(R.id.address);
TextView openingHours = (TextView) findViewById(R.id.openingHours);
TextView contactNo = (TextView) findViewById(R.id.contactNo);
if (selectedSubArea.equals("UK"))
{
this.setTitle(selectedSubArea);
description.setText("desc");
address.setText("add");
latitude = 2.0057378;
longitude = 103.3760577;
openingHours.setText("n/a");
contactNo.setText("n/a");
final Integer[] imageIDs = {
R.drawable.uk_1,
R.drawable.uk_2,
R.drawable.uk_3};
name = selectedSubArea;
desc = description.toString();
add = address.toString();
opening = openingHours.toString();
contact = contactNo.toString();
dbAdapter = new DBAdapter(context);
imageSwitcher = (ImageSwitcher) findViewById(R.id.switcher1);
imageSwitcher.setFactory(this);
imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_in));
imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_out));
Gallery gallery = (Gallery) findViewById(R.id.gallery1);
gallery.setAdapter(new ImageAdapter(this));
gallery.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
imageSwitcher.setImageResource(imageIDs[position]);
}
});
}
}
public View makeView()
{
ImageView imageView = new ImageView(this);
imageView.setBackgroundColor(0x00000000);
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageView.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
return imageView;
}
public class ImageAdapter extends BaseAdapter
{
private Context context;
private int itemBackground;
public ImageAdapter(Context c)
{
context = c;
//---setting the style---
TypedArray a = obtainStyledAttributes(R.styleable.Gallery1);
itemBackground = a.getResourceId(
R.styleable.Gallery1_android_galleryItemBackground, 0);
a.recycle();
}
//---returns the number of images---
public int getCount()
{
return imageIDs.length;
}
//---returns the ID of an item---
public Object getItem(int position)
{
return position;
}
public long getItemId(int position)
{
return position;
}
//---returns an ImageView view---
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView imageView = new ImageView(context);
imageView.setImageResource(imageIDs[position]);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setLayoutParams(new Gallery.LayoutParams(150, 120));
imageView.setBackgroundResource(itemBackground);
return imageView;
}
}

Your global imageIDs array length is ZERO so its displayed nothing. You can't use final array in your case as the objects can varies depending on your selectedSubArea
Else
You can change your ImageAdapter like this then it will work
public class ImageAdapter extends BaseAdapter
{
private Context context;
private int itemBackground;
Integer[] local_imageIDs
public ImageAdapter(Context c, Integer[] local_imageIDs)
{
context = c;
this.local_imageIDs = local_imageIDs;
//---setting the style---
TypedArray a = obtainStyledAttributes(R.styleable.Gallery1);
itemBackground = a.getResourceId(
R.styleable.Gallery1_android_galleryItemBackground, 0);
a.recycle();
}
//---returns the number of images---
public int getCount()
{
return local_imageIDs.length;
}
//---returns the ID of an item---
public Object getItem(int position)
{
return position;
}
public long getItemId(int position)
{
return position;
}
//---returns an ImageView view---
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView imageView = new ImageView(context);
imageView.setImageResource(local_imageIDs[position]);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setLayoutParams(new Gallery.LayoutParams(150, 120));
imageView.setBackgroundResource(itemBackground);
return imageView;
}
}
then set this adapter as
gallery.setAdapter(new ImageAdapter(this, imageIDs));
And remove the global imageIDs

Related

delete selected image from grid view SD card

I created an imageviewer app. Its working fine but when I select a gridview item to delete it, it stops working. On selecting the item, delete button appears . On clicking the delete button ,an alert dialog appears asking for confirmation.I want the file to get deleted after cliking the YES button. But it does not happen. Instead it throws an indexoutofbounds exception. How can I delete selected file succesfully ?
PhotosActivity.java
import static com.example.dell_1.myapp3.ImageViewer.ImageGallery.al_images;
public class PhotosActivity extends AppCompatActivity {
int int_position;
private GridView gridView;
GridViewAdapter adapter;
ArrayList<Model_images> al_menu = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_gallery);
final ImageButton button1 = (ImageButton) findViewById(R.id.button1);
final ImageButton button2 = (ImageButton) findViewById(R.id.button2);
final ImageButton button3 = (ImageButton) findViewById(R.id.button3);
final ImageButton button4 = (ImageButton) findViewById(R.id.button4);
final ImageButton button5 = (ImageButton) findViewById(R.id.button5);
button1.setVisibility(View.GONE);
button2.setVisibility(View.GONE);
button3.setVisibility(View.GONE);
button4.setVisibility(View.GONE);
button5.setVisibility(View.GONE);
gridView = (GridView) findViewById(android.R.id.list);
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("folderPosition", int_position);
i.putExtra("abc", abc);
startActivity(i);
}
});
gridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
for (int j = 0; j < parent.getChildCount(); j++)
parent.getChildAt(j).setBackgroundColor(Color.TRANSPARENT);
// change the background color of the selected element
view.setBackgroundColor(Color.LTGRAY);
button1.setVisibility(View.VISIBLE);
button2.setVisibility(View.VISIBLE);
button3.setVisibility(View.VISIBLE);
button4.setVisibility(View.VISIBLE);
button5.setVisibility(View.VISIBLE);
button3.setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
AlertDialog.Builder builder1 = new AlertDialog.Builder(PhotosActivity.this);
builder1.setMessage("Are you sure you want to delete it ?");
builder1.setCancelable(true);
builder1.setPositiveButton(
"Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
File file = new File( al_menu.get(int_position).getAl_imagepath().get(position));
file.delete();
al_menu.remove(position);
adapter.notifyDataSetChanged();
}
});
builder1.setNegativeButton(
"No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}
});
return true;
}
});
}
}
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(android.R.id.list);
final ImageButton button1 = (ImageButton) findViewById(R.id.button1);
final ImageButton button2 = (ImageButton) findViewById(R.id.button2);
final ImageButton button3 = (ImageButton) findViewById(R.id.button3);
final ImageButton button4 = (ImageButton) findViewById(R.id.button4);
final ImageButton button5 = (ImageButton) findViewById(R.id.button5);
button1.setVisibility(View.GONE);
button2.setVisibility(View.GONE);
button3.setVisibility(View.GONE);
button4.setVisibility(View.GONE);
button5.setVisibility(View.GONE);
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);
}
});
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;
}
}
LOGCAT:
10-20 17:27:02.769 24402-24402/com.example.dell_1.Myapp3 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.dell_1.Myapp3, PID: 24402
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:411)
at com.example.dell_1.myapp3.ImageViewer.PhotosActivity$2$1$1.onClick(PhotosActivity.java:85)
at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:161)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Based on your code, I don't see where the ArrayList al_menu is ever loaded with data. So when your onClick executes and attempts to get item at index 0, you get an IndexOutOfBoundsException exception. Looks like you for got to provide it with default values. Also inside of GridViewAdapter you the declare and instantiate al_menu at the top of the file and then overwrite it inside of the constructor. That is unnecessary and causing an extra object to be used and thrown away and doesn't protect against a NullPointerException later in the adapter because null could be passed into the GridViewAdapter' constructor and you don't check to make sure of that. I recommend adding a condition that checks if the passed in ArrayList is not null and add the values to your ArrayList using a for loop or even removed the instantiation line from the top of the file and do it in the GridViewAdapter's constructor and use in the ArrayList argument as a parameter if it isn't null as parameter when you instantiate your al_menu.
Example:
public class GridViewAdapter extends ArrayAdapter<Model_images> {
Context context;
ViewHolder viewHolder;
ArrayList<Model_images> al_menu;
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);
if(al_menu != null) {
this.al_menu = new ArrayList(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;
}
}

Background color or Images shuffling on scrolling in recyclerview?

I am wondering that my images and color of layouts shuffling when i scrolls downwards or upwards, I created cardview using recyclerview. and set an image(changes color on click like to know if its user's favourite item) and setbackgroundcolor(randomly chossen) to the parent layout to make cardview attractive. but when i scrolls
1. the image that image changes position,
2. the layout background changes color automatically.
I am posting my adapter's code here.
public class TOAdapter extends RecyclerView.Adapter<TOAdapter.ViewHolder> {
JSONArray jsonArray;
private String title;
private String image;
private ImageLoader imageLoader;
private String subtitle;
private String subti;
private Context context;
private ImageView clip;
public TOAdapter(JSONArray jsonArray) {
this.jsonArray = jsonArray;
}
// Create new views (invoked by the layout manager)
#Override
public TOAdapter.ViewHolder onCreateViewHolder(final ViewGroup parent,
int viewType) {
// create a new view
View itemLayoutView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.top_twenty_list, parent, false);
final ViewHolder viewHolder = new ViewHolder(itemLayoutView);
final Random random = new Random(System.currentTimeMillis());// We add 155 since we want at least 155 in each channel.// Then we add to it a random number between 0 and 100.
int r = 155 + random.nextInt(101);
int g = 155 + random.nextInt(101);
int b = 155 + random.nextInt(101);
int color = Color.rgb(r, g, b);
viewHolder.frame.setBackgroundColor(color);
viewHolder.layer.setBackgroundColor(color);
clip = (ImageView) itemLayoutView.findViewById(R.id.ic_clip);
clip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int iColor = Color.parseColor("#0000FF");
int red = (iColor & 0xFF0000) / 0xFFFF;
int green = (iColor & 0xFF00) / 0xFF;
int blue = iColor & 0xFF;
float[] matrix = {0, 0, 0, 0, red
, 0, 0, 0, 0, green
, 0, 0, 0, 0, blue
, 0, 0, 0, 1, 0};
ColorFilter colorFilter = new ColorMatrixColorFilter(matrix);
clip.setColorFilter(colorFilter);
}
});
return viewHolder;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(final ViewHolder viewHolder, int position) {
// - get data from your itemsData at this position
// - replace the contents of the view with that itemsData
// myTypeface = Typeface.createFromAsset(context.getAssets(), "fonts/RobotoCondensedBoldItalic.ttf");
try {
JSONObject obj = jsonArray.getJSONObject(position);
title = obj.getString("title");
image = obj.getString("brand_logo");
subtitle = obj.getString("sub_title");
} catch (JSONException e) {
e.printStackTrace();
}
viewHolder.txtViewTitle.setText(subtitle);
viewHolder.subtitle.setText(title);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
String full_Url = "http://mycompany/assets/new" + image;
viewHolder.thumbnail.setImageUrl(full_Url, imageLoader);
viewHolder.btn_get_deal.setTag(position);
viewHolder.btn_get_deal.setOnClickListener(new View.OnClickListener() {
public JSONObject obj;
public ArrayList<String> offerlist = new ArrayList();
#Override
public void onClick(View view) {
Intent offerpage = new Intent(AppController.getInstance().getApplicationContext(), OfferDetails.class);
Integer pos = (Integer) view.getTag();
try {
obj = jsonArray.getJSONObject(pos);
offerpage.putExtra("jsonObj", obj.toString());
} catch (JSONException e) {
e.printStackTrace();
}
//offerpage.getParcelableArrayListExtra(offerlist);
offerpage.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
AppController.getInstance().getApplicationContext().startActivity(offerpage);
}
});
//viewHolder.txtViewTitle.setTypeface(myTypeface);
}
// inner class to hold a reference to each item of RecyclerView
public static class ViewHolder extends RecyclerView.ViewHolder {
private final NetworkImageView thumbnail;
private final RelativeLayout frame;
private final RelativeLayout layer;
public TextView txtViewTitle;
public TextView subtitle;
public ImageView clip;
public CardView btn_get_deal;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
txtViewTitle = (TextView) itemLayoutView.findViewById(R.id.txttitle_toptwenty);
subtitle = (TextView) itemLayoutView.findViewById(R.id.sub_title_toptwenty);
thumbnail = (NetworkImageView) itemLayoutView.findViewById(R.id.thumbnail_topwenty);
frame = (RelativeLayout) itemLayoutView.findViewById(R.id.frame);
layer = (RelativeLayout) itemLayoutView.findViewById(R.id.layer);
btn_get_deal = (CardView) itemLayoutView.findViewById(R.id.card_view);
}
}
// Return the size of your itemsData (invoked by the layout manager)
#Override
public int getItemCount() {
return jsonArray.length();
}
}
I have created a working example of what you are trying to accomplish. The source of the errors you experience is mostly that you don't understand view recycling. I am not going to explain the whole thing to you now, but anyway here is the example:
For the example I used this layout for each row:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
android:id="#+id/background"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="80dp">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"/>
</FrameLayout>
I used this model:
public class ExampleModel {
private final int mColor;
private final String mText;
public ExampleModel(int color, String text) {
mColor = color;
mText = text;
}
public int getColor() {
return mColor;
}
public String getText() {
return mText;
}
}
And this view holder:
public class ExampleViewHolder extends RecyclerView.ViewHolder {
private final FrameLayout mBackground;
private final TextView mTextView;
public ExampleViewHolder(View itemView) {
super(itemView);
mBackground = (FrameLayout) itemView.findViewById(R.id.background);
mTextView = (TextView) itemView.findViewById(R.id.textView);
}
public void bind(ExampleModel model) {
mBackground.setBackgroundColor(model.getColor());
mTextView.setText(model.getText());
}
}
As you can see nothing special, the Adapter implementation is equally simple:
public class ExampleAdapter extends RecyclerView.Adapter<ExampleViewHolder> {
private final LayoutInflater mInflater;
private final List<ExampleModel> mModels;
public ExampleAdapter(Context context, List<ExampleModel> models) {
mInflater = LayoutInflater.from(context);
mModels = models;
}
#Override
public ExampleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
final View itemView = mInflater.inflate(R.layout.item_example, parent, false);
return new ExampleViewHolder(itemView);
}
#Override
public void onBindViewHolder(ExampleViewHolder holder, int position) {
final ExampleModel model = mModels.get(position);
holder.bind(model);
}
#Override
public int getItemCount() {
return mModels.size();
}
}
And you use the whole thing like this:
final Random mRandom = new Random(System.currentTimeMillis());
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
final List<ExampleModel> models = new ArrayList<>();
for (int i = 0; i < 100; i++) {
final int randomColor = generateRandomPastelColor();
models.add(new ExampleModel(randomColor, String.valueOf(i)));
}
final ExampleAdapter adapter = new ExampleAdapter(getActivity(), models);
recyclerView.setAdapter(adapter);
}
public int generateRandomPastelColor() {
final int baseColor = Color.WHITE;
final int red = (Color.red(baseColor) + mRandom.nextInt(256)) / 2;
final int green = (Color.green(baseColor) + mRandom.nextInt(256)) / 2;
final int blue = (Color.blue(baseColor) + mRandom.nextInt(256)) / 2;
return Color.rgb(red, green, blue);
}
This should do what you are looking for and you can use it as an example of how to implement your Adapter.
I got the same problem ,when i used the radioButton in my listView row, I solved it. As in every scrolling the Cache is cleared, you have to store the changed data in every row. just check my code
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
// if(position==0)
// Toast.makeText(context, ""+QuestionViewPageAdapter.mRadioGroupData, Toast.LENGTH_SHORT).show();
final ViewHolder viewHolder;
View row=convertView;
radioButton=new RadioButton[Integer.parseInt(mNoOfCategoryGreading)];
LayoutInflater inflater =LayoutInflater.from(context);//(LayoutInflater)context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.question_row, parent, false);
viewHolder=new ViewHolder();
viewHolder.tv_qContent=(TextView)row.findViewById(R.id.tv_question);
viewHolder.rg=(RadioGroup)row.findViewById(R.id.rgrp);
for(int i=0;i<Integer.parseInt(mNoOfCategoryGreading);i++)
{
radioButton[i]=new RadioButton(context);
radioButton[i].setLayoutParams(new RadioGroup.LayoutParams(0, LayoutParams.WRAP_CONTENT,1f));
//1f for layout_weight="1"
radioButton[i].setId(i);
radioButton[i].setText(""+(i+1));
viewHolder.rg.addView(radioButton[i]);
}
row.setTag(viewHolder);
for(int i=0;i<QuestionViewPageAdapter.mRadioGroupData.size();i++){
int p=Integer.parseInt(""+QuestionViewPageAdapter.mRadioGroupData.get(i).get("position"));
String id=QuestionViewPageAdapter.mRadioGroupData.get(i).get("Id");
if(p!=-1 && id.equals(""+data.get(position).get(AppData.question_Set_category_QuestionID)))
{//radioButton[p].setSelected(true);
viewHolder.rg.check(p-1);}
//Toast.makeText(context, "Yes "+p, Toast.LENGTH_LONG).show();}
}
viewHolder.tv_qContent.setText((position+1)+". "+data.get(position).get(AppData.question_Set_category_QuestionContent));
viewHolder.tv_qContent.setTypeface(typeface_muso_regular300);
viewHolder.rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
String s=data.get(position).get(AppData.question_Set_category_QuestionID);
isAvailabel(s);
int radioButtonID = viewHolder.rg.getCheckedRadioButtonId();
View radioButton = viewHolder.rg.findViewById(radioButtonID);
int idx = viewHolder.rg.indexOfChild(radioButton);
HashMap<String, String> map=new HashMap<String, String>();
map.put("position", ""+(idx+1));
map.put("Id", ""+data.get(position).get(AppData.question_Set_category_QuestionID));
map.put("CategoryId", ""+mCategoryId);
QuestionViewPageAdapter.mRadioGroupData.add(map);
}
});
return row;
}
private void isAvailabel(String qId){
for(int i=0;i<QuestionViewPageAdapter.mRadioGroupData.size();i++){
if(qId.equals(QuestionViewPageAdapter.mRadioGroupData.get(i).get("Id"))){
position=i;
QuestionViewPageAdapter.mRadioGroupData.remove(i);
}
}
}
class ViewHolder {
TextView tv_qContent ,tv_1,tv_2,tv_3;
RadioGroup rg;
RadioButton rBtn1,rBtn2,rBtn3,rBtn4,rBtn5;
}
After days of struggle and headache, i have found a very simple solution.
In your adapter you just need to override 2 methods.
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
Helped me resolve the shuffling issue of recycler view.
In my case overriding getItemId and setting sethasStableIds to true solved the shuffling issue.
in adapter:
#Override
public long getItemId(int position) {
Object listItem = feeds.get(position);
return listItem.hashCode();
}
in main activity/fragment :
adapter = new FeedAdapter(feeds, getContext());
adapter.setHasStableIds(true);

How to keep custom listview items when they are out of screen?

I am trying to design a menu like this:
It almost works, however there is a problem. The menu works fine at start, but after scrolling down and up again, the items are gone and downloaded again and it takes a little time. Is there a way to set a number of elements to create at start and keep them from disappearing?
Here is my code:
public class MyActivity extends Activity implements AdapterView.OnItemClickListener {
String headers[];
String image_urls[];
List<MyMenuItem> menuItems;
ListView mylistview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
menuItems = new ArrayList<MyMenuItem>();
headers = getResources().getStringArray(R.array.header_names);
image_urls = getResources().getStringArray(R.array.image_urls);
for (int i = 0; i < headers.length; i++) {
MyMenuItem item = new MyMenuItem(headers[i], image_urls[i]);
menuItems.add(item);
}
mylistview = (ListView) findViewById(R.id.list);
MenuAdapter adapter = new MenuAdapter(this, menuItems);
mylistview.setAdapter(adapter);
mylistview.setOnItemClickListener(this);
}
}
public class MyMenuItem {
private String item_header;
private String item_image_url;
public MyMenuItem(String item_header, String item_image_url){
this.item_header=item_header;
this.item_image_url=item_image_url;
}
public String getItem_header(){
return item_header;
}
public void setItem_header(String item_header){
this.item_header=item_header;
}
public String getItem_image_url(){
return item_image_url;
}
public void setItem_image_url(String item_image_url){
this.item_image_url=item_image_url;
}
}
public class MenuAdapter extends BaseAdapter{
Context context;
List<MyMenuItem> menuItems;
MenuAdapter(Context context, List<MyMenuItem> menuItems) {
this.context = context;
this.menuItems = menuItems;
}
#Override
public int getCount() {
return menuItems.size();
}
#Override
public Object getItem(int position) {
return menuItems.get(position);
}
#Override
public long getItemId(int position) {
return menuItems.indexOf(getItem(position));
}
private class ViewHolder {
ImageView ivMenu;
TextView tvMenuHeader;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.menu_item, null);
holder = new ViewHolder();
holder.tvMenuHeader = (TextView) convertView.findViewById(R.id.tvMenuHeader);
holder.ivMenu = (ImageView) convertView.findViewById(R.id.ivMenuItem);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
MyMenuItem row_pos = menuItems.get(position);
Picasso.with(context)
.load(row_pos.getItem_image_url())
// .placeholder(R.drawable.empty)
// .error(R.drawable.error)
.into(holder.ivMenu);
holder.tvMenuHeader.setText(row_pos.getItem_header());
Log.e("Test", "headers:" + row_pos.getItem_header());
return convertView;
}
}
Possibly you can implement lazy loading with some sort of caching of images or whatever you are downloading...
You say the images are donwloaded, i assume that the images are coming from internet. Implement a custom cache for http download or download and store the images in one place before you use

How to refresh viewpager after delete operation

In my app ,i used view pager to show my image gallery .
after deleteing any image from my gallery , view pager should get updated.
My Activity
public class FullScreenViewActivityForSelfImage extends Activity{
#SuppressWarnings("unused")
private Utils utils;
private FullScreenImageAdapterForSelfImage adapter;
private static ViewPager viewPager;
DatabaseHelper db;
ArrayList<Image> aryimages;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen_view);
db=new DatabaseHelper(this);
viewPager = (ViewPager) findViewById(R.id.pager);
aryimages= db.getimages();
Intent i = getIntent();
int position = i.getIntExtra("position", 0);
adapter = new FullScreenImageAdapterForSelfImage(FullScreenViewActivityForSelfImage.this,
aryimages,this);
viewPager.setAdapter(adapter);
// displaying selected image first
viewPager.setCurrentItem(position);
}
public static ViewPager getAdapter() {
return viewPager;
}
}
My Adapter Class
public class FullScreenImageAdapterForSelfImage extends PagerAdapter
{
private Activity _activity;
private ArrayList<Image> _imagePaths;
ArrayList<Image> aryimages;
public ImageListAdapter ImageListAdapter;
private LayoutInflater inflater;
private Context context;
int columnWidth,width,cellWidth,padding,height;
DatabaseHelper db;
int i;
String id,name;
// constructor
public FullScreenImageAdapterForSelfImage(Activity activity,
ArrayList<Image> aryimages,Context context) {
this._activity = activity;
this._imagePaths = aryimages;
this.context = context;
db= new DatabaseHelper(_activity);
Display display = activity.getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
width = size.x;
height = size.y;
}
My Adapter where delete service is called
btndel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(v.getContext());
alertDialog.setTitle("Confirm Delete...");
alertDialog.setMessage("You are about to delete all images of this product continue");
alertDialog.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
// Write your code here to execute after dialog
name = _imagePaths.get(position).Image_name.toString();
String imei=db.SelectImeiNo();
id=db.getidbyname(name);
System.out.println("selected imei = "+imei);
System.out.println("selected id = "+id);
dialog.cancel();
WebServiceTask wst = new WebServiceTask(WebServiceTask.POST_TASK, context , "Deleting Image...");
wst.execute(new String[] { Service_url });
}
});
In Adapter i tried to refresh
public void handleResponse(String response) {
System.out.println("handle REsponse...got result..."+response);
if(response.equalsIgnoreCase("0"))
{
System.out.println("!!!!!!!!!!Server Busy try again latter!!!!!!!!!!!!!!!!");
Toast.makeText(context.getApplicationContext(), "Server Busy try again latter", Toast.LENGTH_LONG).show();
}
else if(response.equalsIgnoreCase("1"))
{
System.out.println("!!!!!!!!!!!!Image deleted!!!!!!!!!!!!!!!!!!!");
Toast.makeText(context.getApplicationContext(), "Image deleted", Toast.LENGTH_LONG).show();
db.deleteImageSelected(id);
_imagePaths.remove(i);
ImageListAdapter.notifyDataSetChanged();
}
}
Image Adapter
public class ImageListAdapter extends BaseAdapter {
//private Context context;
private ArrayList<Image> Img;
private LayoutInflater inflater = null;
public ImageListAdapter(Context context, ArrayList<Image> Image) {
// this.context = context;
this.Img = Image;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return Img.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#SuppressLint("InflateParams")
#SuppressWarnings("unused")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
if (convertView == null) {
view = inflater.inflate(R.layout.imageshow, null);
} else {
view = convertView;
}
ImageView iv= (ImageView) view.findViewById(R.id.imageshowView1);
TextView name= (TextView) view.findViewById(R.id.Imageshownametv);
TextView id= (TextView) view.findViewById(R.id.Imageshowidtv);
TextView desc= (TextView) view.findViewById(R.id.Imageshowimagedesc);
id.setText(Img.get(position).Image_id);
byte[] I= Img.get(position).image;
System.out.println("Byte array of the image "+I);
Bitmap bp=BitmapFactory.decodeByteArray(I, 0, I.length);
iv.setImageBitmap(bp);
return view;
}
}
But it is not done
so please help me..

why is notifyDataSetChanged() not working in my code?

Why is my code not working? I have already tried using notifyDataSetChanged(), or using invalid() for my listview, or using .setAdapter() again for my adapter, but its still not working please help me.
public class ListDel extends Activity{
ListView mylist_del;
ListViewAdapter listViewAdapter_del;
TypedArray images_del;
ImageView bin_image;
private static String[] names, ages;
storageListImplementation lists = new storageListImplementation();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.del_layout);
names = lists.getNames();
ages = lists.getAges();
images_del = getResources().obtainTypedArray(R.array.icons);
bin_image = (ImageView)findViewById(R.id.del_image_icon);
listViewAdapter_del = new ListViewAdapter(this);
mylist_del = (ListView)findViewById(R.id.listview_delete);
mylist_del.setAdapter(listViewAdapter_del);
}
private class ListViewAdapter extends BaseAdapter{
private LayoutInflater mInflater;
public ListViewAdapter(Context context){
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return names.length;
}
public Object getItem(int pos) {
return pos;
}
public long getItemId(int position) {
return position;
}
private OnClickListener binClick(ImageView img, final int position, String name) {
return new View.OnClickListener(){
public void onClick(View v) {
lists.del(names[position]);
mylist_del.invalidate();
//mylist_del.setAdapter(listViewAdapter_del);
listViewAdapter_del.notifyDataSetInvalidated();
listViewAdapter_del.notifyDataSetChanged();
//newlistviewadap();
//mylist_del.setAdapter(new ListViewAdapter(this));
//listViewAdapter_del.notifyDataSetChanged();
//String addSuccessful = "You have successfully deleted "+names[position]+" and his/her information in you database";
//Toast.makeText(getApplicationContext(), addSuccessful, Toast.LENGTH_LONG).show();
//ListDel.this.finish();
}
};
}
public void newlistviewadap(){
mylist_del.setAdapter(listViewAdapter_del);
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder textView;
if(convertView==null){
convertView = mInflater.inflate(R.layout.del_listview_row, null);
textView = new ViewHolder();
textView.text = (TextView) convertView.findViewById(R.id.del_values_row);
textView.age = (TextView) convertView.findViewById(R.id.del_age_row);
textView.image = (ImageView) convertView.findViewById(R.id.del_image);
textView.delbutton = (ImageView) convertView.findViewById(R.id.del_image_icon);
convertView.setTag(textView);
}else{
textView = (ViewHolder) convertView.getTag();
}
textView.text.setText(names[position]);
textView.age.setText(ages[position]);
textView.image.setImageDrawable(images_del.getDrawable(position));
textView.delbutton.setOnClickListener(binClick( textView.delbutton, position, names[position]));
return convertView;
}
}
static class ViewHolder{
TextView text;
TextView age;
ImageView image;
ImageView delbutton;
}
}
Try removing
listViewAdapter_del.notifyDataSetInvalidated();
Once you've called it, mylist_del will not retrieve more data from listViewAdapter_del, so only keep the code below and try again:
lists.del(names[position]);
listViewAdapter_del.notifyDataSetChanged();

Categories