Problem passing a parameter to a different class - java

I've got a rather peculiar problem. I am trying to pass a number of parameters to a method in a different class, and three out of the four parameters are being passed just fine. The fourth, however, is returning 0 (zero) regardless of what I seem to do.
I am initializing the second class, ImageLoader, without any issues.
Here's the call in question - I've added comments to explain my problem:
imageLoader.DisplayImage(coverFileNames.get(position), Main.this, (ImageView) convertView, position); // coverFileNames.get(position) works great and returns the correct filename based on the position - position on its own, however, doesn't!
And here's the DisplayImage method:
public int position;
public void DisplayImage(String fileUrl, Activity activity, ImageView imageView, final int pos) {
position = pos; // this is 0 no matter what I do
imageViews.put(imageView, fileUrl);
queuePhoto(fileUrl, activity, imageView);
imageView.setImageResource(R.drawable.noposterlarge);
}
Any ideas? Thanks.
EDIT:
Here's the GetView method:
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = (ImageView) new ImageView(Main.this);
}
// Create new file for the file path of the movie
File file = new File(videoUrls.get(position));
// Create variables for potential custom art check
boolean potentialImage = false;
String ImageFile = null;
String[] potentialImageFiles = new String[]{file.getAbsolutePath().substring(0, file.getAbsolutePath().lastIndexOf(".")) + ".jpg",
file.getAbsolutePath().substring(0, file.getAbsolutePath().lastIndexOf(".")) + ".jpeg",
file.getAbsolutePath().substring(0, file.getAbsolutePath().lastIndexOf(".")) + ".JPG",
file.getAbsolutePath().substring(0, file.getAbsolutePath().lastIndexOf(".")) + ".JPEG"};
// Check if each file exists and return if one does
for (String potentialFile : potentialImageFiles) {
if (!potentialImage) {
if (new File(potentialFile).exists()) {
potentialImage = true;
ImageFile = potentialFile;
}
}
}
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
options.inPreferredConfig = Config.RGB_565;
// Check if there's a custom cover art
if (potentialImage) {
Log.d("TEST", "POS: " + position); // this returns the correct value
imageLoader.DisplayImage(ImageFile, Main.this, (ImageView) convertView, position);
} else {
Log.d("TEST", "POS: " + position); // this returns the correct value
imageLoader.DisplayImage(coverFileNames.get(position), Main.this, (ImageView) convertView, position);
}
return convertView;
}
And again, here's the DisplayImage method:
public void DisplayImage(String fileUrl, Activity activity, ImageView imageView, final int pos) {
Log.v("Testing", "position = " + pos); // This returns 0, which is not correct
imageViews.put(imageView, fileUrl);
queuePhoto(fileUrl, activity, imageView);
imageView.setImageResource(R.drawable.noposterlarge);
}

this is simply impossible
Add to top of DisplayImage
Log.v("DisplayImage", "position = " + position);
If it is 0
Change the calling code from
imageLoader.DisplayImage(coverFileNames.get(position), Main.this, (ImageView) convertView, position);
to
imageLoader.DisplayImage(coverFileNames.get(position), Main.this, (ImageView) convertView, 2);
Now, will it show 2? It must
It means that in your calling code in the line imageLoader.DisplayImage() position has always been 0 for some reason.
coverFileNames.get(position) is always returning the String at position=0
Try removing the final modifier from your DisplayImage function
public void DisplayImage(String fileUrl, Activity activity, ImageView imageView, int pos)

Related

How to use setVisibility on integer array in adapter list view by onclick on ImageView in android

I'm trying to invisible an image when it is clicked by storing images from drawable into integer array using adapter list view, but I'm unable to get it. This is the code I'm using:
When i click on an image it should get invisible.I am storing images in int array and applying setVisibilty invisible but its not working.i want an image to be displayed in centre of screen and the one which is clicked should get invisible.i am trying to store images in an integer array and setting it up in adapter list.i am calling this function
imageIDs[position].setVisible(false);
Integer[] imageIDs = {
R.drawable.c2,
R.drawable.c3,
R.drawable.c4,
R.drawable.c5,
R.drawable.c6,
R.drawable.c7,
R.drawable.c8
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Note that Gallery view is deprecated in Android 4.1---
Gallery gallery = (Gallery) findViewById(R.id.gallery1);
//Adapter list
gallery.setAdapter(new ImageAdapter(this));
gallery.setOnItemClickListener(new OnItemClickListener() {
//onclick event
public void onItemClick(AdapterView<?> parent, View v, int position,long id)
{//displaying image clicked i am trying to invisible this pic when click
Toast.makeText(getBaseContext(),"pic" + (position + 1) + " selected",//dispplpaying msg
Toast.LENGTH_SHORT).show();
//imageIDs[position].setVisible(false);
// display the images selected
ImageView imageView = (ImageView) findViewById(R.id.image1);
imageView.setImageResource(imageIDs[position]);
//setting image on screen from using xml
}
});
}
public class ImageAdapter extends BaseAdapter {
private Context context;
private int itemBackground;
public ImageAdapter(Context c)
{
context = c;
// sets a grey background; wraps around the images
TypedArray a =obtainStyledAttributes(R.styleable.MyGallery);
itemBackground = a.getResourceId(R.styleable.MyGallery_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;
}
// returns the ID of an item
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);
//imageIDs[position].setVisible(false);
//i am trying it here but its not working
imageView.setImageResource(imageIDs[position]);
imageView.setLayoutParams(new Gallery.LayoutParams(100, 100));
imageView.setBackgroundResource(itemBackground);
return imageView;
}
}
}
I'm assuming you're trying to use this code:
//imageIDs[position].setVisible(false);
If so then what you're doing is calling setVisible on an Integer, which does not have that method. What you need to do is get a reference to the ImageView in which the image is being displayed and then call setVisibility(View.INVISIBLE) or setVisibility(View.GONE) on it.
Also it seems like you're trying to set the image to invisible but then you go and put the same resource back into the ImageView so I'm not sure what you're trying to do there.

ArrayAdapter position is wrong

public class SongListAdapter_AddMode extends ArrayAdapter{
Context context;
ArrayList<Song> songs;
public SongListAdapter_AddMode(Context context, ArrayList<Song> songs) {
super(context, R.layout.list_item1_addmode, songs );
this.songs = songs;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
ViewHolder holder;
final int pos = position;
Log.d("TAG", "position :" + position);
Song currentSong = songs.get(position);
Log.d("TAG", "position : " + position );
if( convertView == null ){
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate( R.layout.list_item1_addmode, parent, false );
holder.titleLabel = (TextView) convertView.findViewById( R.id.topLabel );
holder.artistLabel = (TextView) convertView.findViewById( R.id.bottomLabel );
holder.cover = (ImageView) convertView.findViewById( R.id.list_image );
holder.button = (ImageView) convertView.findViewById(R.id.addButton);
holder.button.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
Log.d("TAG", "pos" + pos );
}
});
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
Uri coverPath = ContentUris.withAppendedId(Uri.parse("content://media/external/audio/albumart"), currentSong.getID() );
Picasso.with(context).load( coverPath ).error( R.drawable.untitled ).into( holder.cover );
holder.titleLabel.setText( currentSong.getName() );
holder.artistLabel.setText( currentSong.getArtistName() );
return convertView;
}
private class ViewHolder {
TextView titleLabel;
TextView artistLabel;
ImageView cover;
ImageView button;
}
}
Well this is a small example of what an ArrayAdapter might look like. As you can see in the getView() method, I get the currentSong from a list which is actually very huge. It contains 1600~ Songs. When I print the position to the LogCat, it says 0 up to 7. How am I getting the correct position in the song list but when I print it, it is totally different?
I ALWAYS get the correct song. Even in the 900~ and above. But the position(LogCat) is always from 0 up to 7...
I need to get the current row. I want to add an onClickListener() to a button from the current View in this method and when I click it, I want to do something which I cannot do with an onItemClickListener() on the ListView.
It seems that you set the button click listener to print the position of the recyclable views thus you get 0-7.
Instead set the listener outside the if (convertview == null) check.
I ALWAYS get the correct song
of course since the code is correct
But the position(LogCat) is always from 0 up to 7...
This is due to how the ListView recycles its rows. 7 items are visible on the screen of your test device. See this post
You should override getCount:
#Override
public int getCount(){
return songs.size();
}
Because it is essential for correct displaying the list, but returns 0 b default.
When your view has wrong position ids or displays wrong items in your autocomplete dropdown view, then instantiate your view like this (Kotlin):
val view: View = convertView ?: LayoutInflater.from(context).inflate(resourceId, parent, false)

Android - findViewWtihTag returns null

The findViewWithTag in this activity is returning null, but the Log in the CustomExpandableListAdapter outputs correctly. What am I doing wrong here?
public class CustomExpandableListAdapter extends BaseExpandableListAdapter {
//normal stuff
public View getGroupView(int groupPosition, boolean isLastChild,
View view, ViewGroup parent) {
CustomObject group = (CustomObject) getGroup(groupPosition);
//normal stuff
LinearLayout toggle = (LinearLayout) view.findViewById(R.id.toggle);
//group.getId() returns an int
toggle.setTag("toggle" + group.getId());
Log.i("BBBBBtoggleadapterBBBBBB", toggle.getTag().toString());
return view;
}
}
public class MainActivity extends BaseListActivity {
//normal stuff
//this is an xml onClick
public void toggleView(View view) {
String groupId = view.getTag().toString();
//LinearLayout toggle = (LinearLayout) view.findViewWithTag("toggle " + groupId);
Log.i("BBBBBBBBBtoggleactivityBBBBBBBBBB", "toggle" + groupId);
/*if (toggle == null) {
Toast.makeText(getBaseContext(), "null", Toast.LENGTH_LONG).show();
}*/
}
}
edit:updated code, Logged "toggle" + id in activity and adapter and they are identical
I figured it out. findViewWithTag looks for child tags that match. The LinearLayout I was trying to identify is not a child of the button who's onClick triggered toggleView. So, I needed to go up (2 levels, in this case) to find it.
View parent = (View) view.getParent().getParent();
LinearLayout toggle = (LinearLayout) parent.findViewWithTag("toggle" + groupId);
Your tags aren't the same. "id " + group.getId() != "toggle " + groupId

Set list view height without TextView with adapter

I have a ListView which is supposed to become a menu with two drawables and two text views per row.
Activity Code:
ArrayList<MenuItem> itemArray = new ArrayList<MenuItem>();
itemArray.add(new MenuItem("Headertexxt", "subbtexdt"));
itemArray.add(new MenuItem("asf", "asf"));
ListView listView = (ListView) findViewById(R.id.listViewCM);
String[] array = getResources().getStringArray(R.array.buttonsCM);
int[] images = new int[] { R.drawable.btn_car, R.drawable.btn_star, R.drawable.btn_bag};
listView.setAdapter(new HomeScreenButtonsAdapterSubtext(this, R.layout.row,
itemArray, images, R.drawable.list_arrow));
Utils.setListViewHeightBasedOnChildren(listView);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
findViewById(R.id.buttonCreditCompilation).performClick();
break;
case 1:
findViewById(R.id.buttonYourCredits).performClick();
break;
}
}
});
Adapter code:
public class HomeScreenButtonsAdapterSubtext extends ArrayAdapter<MenuItem> {
private Drawable[] drawables;
private Drawable arrowDrawable;
private ArrayList<MenuItem> items;
public HomeScreenButtonsAdapterSubtext(Context context, int resourceId,
ArrayList<MenuItem> items, int[] images, int arrowImage) {
super(context, resourceId, items);
this.items = items;
Resources resources = context.getResources();
if (images != null) {
drawables = new Drawable[images.length];
int i = 0;
for (int id : images) {
Drawable drawable = resources.getDrawable(id);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight());
drawables[i++] = drawable;
}
}
arrowDrawable = resources.getDrawable(arrowImage);
arrowDrawable.setBounds(0, 0, arrowDrawable.getIntrinsicWidth(),
arrowDrawable.getIntrinsicHeight());
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);
if (v instanceof TextView) {
Drawable dr = drawables != null ? drawables[position %
drawables.length] : null;
((TextView) v).setCompoundDrawables(dr, null, arrowDrawable, null);
Utils.setFont((TextView) v);
}
// View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.row, null);
}
MenuItem station = items.get(position);
if (station != null) {
TextView tt = (TextView) v.findViewById(R.id.headerText);
TextView bt = (TextView) v.findViewById(R.id.subText);
if (tt != null) {
tt.setText(station.getHeaderText());
}
if (bt != null) {
bt.setText(station.getSubText());
}
}
return v;
}
The problem I have right now is that I can't set the listview height based on the children. I'm trying to do that here: Utils.setListViewHeightBasedOnChildren(listView); but getting the error: arrayadapter requires the resource id to be a textview at this row. Does anyone know a solution for this?
Can I use some other method for setting the ListView height?
Thanks
but getting the error: arrayadapter requires the resource id to be a
textview at this row.
R.layout.row is a layout file which it doesn't have just a TextView. If you call the super constructor you have used and you also call the super.getView(in the getView method) method in the adapter, then ArrayAdapter will complain as it expects a single widget in the layout file passed to it(a single TextView).
I don't understand why you have that piece of code in the getView method(with the super call) when you know precisely that the row can't be an instance of Textview .
I'm not sure about setting the height of the ListView either, if you're trying to show all the rows of the ListView, don't do it(as you make the ListView basically useless). If you still want to do this, then it's better to lose the ListView and build the row layouts manually.
In fact it does not really make sense to set the height of ListView depending on its content.
Because the whole point of a ListView is to make its content scrollable (however big it is)...so it is supposed to have a fixed height.

How do I set the text color in a SeparatedListAdapter?

I am using Jeff Sharkey's SeparatedListAdapter and I would like to set the text color, but I'm not sure how.
To give you some background on his adapter, he subclassed a BaseAdapter similar to a simple Android list. So, I tried to set the text color in the getView() method like this (Your can see my attempt in between the commented section):
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
int sectionnum = 0;
for(Object section : this.sections.keySet()) {
Adapter adapter = sections.get(section);
int size = adapter.getCount() + 1;
// check if position inside this section
if(position == 0) return headers.getView(sectionnum, convertView, parent);
if(position < size)
{
/***** I added this section to try to set the text color ***/
TextView captionTV = (TextView)adapter.getView(position, convertView, parent).findViewById(R.id.list_complex_caption);
captionTV.setTextColor(R.color.black;);
TextView titleTV = (TextView)adapter.getView(position, convertView, parent).findViewById(R.id.list_complex_title);
titleTV.setTextColor(R.color.black;);
/***** end add *****/
return adapter.getView(position - 1, convertView, parent);
}
// otherwise jump into next section
position -= size;
sectionnum++;
}
return null;
}
But what happens is that it sets the text color for the first cell, but does not set it for the rest.
Any ideas?
Hm. Nifty adapter.
The first thing to note here - modifying Views in the way you're doing is something best left to the layouts you use in the various section adapters, i.e. if you want black text, use an item layout that has black text.
To do it in code anyway you should not repeatedly call #getView(int, View, ViewGroup) on the sub-section adapters, instead do like this:
/**
* {#inheritDoc}
*/
public View getView(int position, View convertView, ViewGroup parent) {
int sectionnum = 0;
for(Object section : this.sections.keySet()) {
Adapter adapter = sections.get(section);
int size = adapter.getCount() + 1;
// check if position inside this section
if(position == 0) return headers.getView(sectionnum, convertView, parent);
if(position < size){
View view = adapter.getView(position - 1, convertView, parent);
TextView captionTV = (TextView) view.findViewById(R.id.list_complex_caption);
captionTV.setTextColor(R.color.black);
TextView titleTV = (TextView) view.findViewById(R.id.list_complex_title);
titleTV.setTextColor(R.color.black);
return view;
}
// otherwise jump into next section
position -= size;
sectionnum++;
}
return null;
}
Try to do it in bindView override the bindView function e.g.
#Override
public void bindView(View v, Context context, Cursor c) {
String name = c.getString(nameCol);
TextView captionTV = (TextView) v.findViewById(R.id.list_complex_caption);
captionTV.setTextColor(R.color.black);
}

Categories