Picasso on custom listview - java

I'm a beginner with android and am trying to use the image from google places API to my custom listview. I am trying to do this using Picasso. I can get the text no problem but when I'm trying to attach the image from the url it gives me an "Target must not be null" error. Any comments/help/suggestions is appreciated.
My custom listrow places_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="1">
<ImageView
android:id="#+id/placeicon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.10"/>
<TextView
android:id="#+id/placeinfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawablePadding="20dp"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/placeicon"
android:layout_toEndOf="#+id/placeicon" />
</RelativeLayout>
My Async PostExecute code:
ImageView places_icon = (ImageView) findViewById(R.id.placeicon);
venuesfound = (ArrayList) parsedataFound(result);
ArrayList<String> venuesList = new ArrayList<>();
for(int i = 0; i<venuesfound.size();i++){
if(venuesfound.get(i).getImageURL() != null){
Picasso.with(getApplicationContext())
.load(venuesfound.get(i).getImageURL())
.into(places_icon);
}
venuesList.add(venuesfound.get(i).getName()
+ "\nOpen: " + venuesfound.get(i).getOpenNow()
+ "\n(" + venuesfound.get(i).getCategory() + ")");
}
placesList = (ListView) findViewById(R.id.places_list);
placesAdapter = new ArrayAdapter(DisplayPlacesActivity.this, R.layout.places_layout, R.id.placeinfo, venuesList);
placesList.setAdapter(placesAdapter);
Logcat:
java.lang.IllegalArgumentException: Target must not be null.
at com.squareup.picasso.RequestCreator.into(RequestCreator.java:618)
at com.squareup.picasso.RequestCreator.into(RequestCreator.java:601)
at com.example.johnchy.samplegui.DisplayPlacesActivity$dataRequest.onPostExecute(DisplayPlacesActivity.java:102)
at com.example.johnchy.samplegui.DisplayPlacesActivity$dataRequest.onPostExecute(DisplayPlacesActivity.java:56)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5419)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1187)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
at dalvik.system.NativeStart.main(Native Method)
Again, any help is appreciated!

The problem is, you try to attach the image to an ImageView, that is not there yet. Since you want to show the image in your list, you need to move the attachment into the adapter, since this is where you create the new ImageView. You will need to create a new ArrayAdapter for this purpose:
public class PicassoAdapter extends ArrayAdapter<String> {
public PicassoAdapter(List<String> urls, Context context){
super(context, 0, urls);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
PlaceViewHolder holder;
//ListView tries to reuse invisible Row-Views to save memory, thats why this method can be called with null OR actually a ready View
if(convertView == null){
//in this case we need to create a new View
//create a holder Object that we will attach to the view
holder = new PlaceViewHolder();
//in this line we actually create a new row from the xml-file
convertView = View.inflate(getContext(), R.layout.places_layout, parent, false);
//we attach the Image- and Text-View to our holder, so we can access them in the next step
holder.placeIcon = (ImageView)convertView.findViewById(R.id.placeicon);
holder.placeInfo = (TextView)convertView.findViewById(R.id.placeinfo);
convertView.setTag(holder)
} else {
//if the view is already created, simply get the holder-object
holder = (PlaceViewHolder)convertView.getTag();
}
//I assume the URL is a String, if you need another Type, simply change it here and in class declaration
String url = getItem(position);
Picasso.with(getContext())
.load(url)
//now we have an ImageView, that we can use as target
.into(holder.placeIcon);
//you can set the info here
holder.placeInfo.setText("test");
}
}
//we need this class as holder object
public static class PlaceViewHolder {
private ImageView placeIcon;
private TextView palceInfo;
}
}
now you can use this adapter in your List:
placesList.setAdapter(new PicassoAdapter(urls, DisplayPlacesActivity.this));
beware, that the performance of this code may be very bad, since we try to load the image on the UI-Thread, but I think it's ok as an example

Related

Spinner updating only on user actions

I have IconText that has image and text views inside it, both class and xml.
I then populate the Spinner inside of the MainActivity with these IconTexts, using extended BaseAdapter (IconTextAdapter) as adapter.
Now, IconText works fine (shows as it should).
Spinner however doesn't.
When I start the app, it shows the first IconText as it should.
When I open the choose dialog, everything is showing as it should.
When I select another item, the choose dialog collapses and spinner displays no IconText (ie. only "arrow down" for opening choose dialog).
I can still open the choose dialog and choose another.
I've noticed that if I exit from app (return button, not really quiting the app) and enter again that the proper IconText is shown.
I guess that the fault lies with the adapter?
I will try avoiding posting a lot of code [:
IconText.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView android:id="#+id/it_image"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:src="#drawable/home"/>
<TextView
android:id="#+id/it_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="20sp"
android:text="ABC"
android:textColor="#color/black_overlay"
android:textSize="20sp"
android:textStyle="bold" />
</LinearLayout>
IconText.java
public class IconText {
static LayoutInflater inflator;
public ImageView icon;
public TextView text;
public View view;
public IconText(String title, int icon_id){
Log.d("IconText", "Create");
view = inflator.inflate(R.layout.icon_text, null);
text = (TextView) view.findViewById(R.id.it_text);
icon = (ImageView) view.findViewById(R.id.it_image);
text.setText(title);
icon.setImageResource(icon_id);
}
public static void initInflator(Context context){
if(inflator != null) return;
Log.d("IconText", "Init inflator");
inflator = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
}
IconTextAdapter.java
public class IconTextAdapter extends BaseAdapter implements SpinnerAdapter{
public ArrayList<IconText> items;
public IconTextAdapter(){
super();
items = new ArrayList<>();
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int arg0) {
return items.get(arg0);
}
#Override
public long getItemId(int position) {
return items.get(position).view.getId();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
return items.get(position).view;
}
}
MainActivity, relevant code
void initFilter(){
Log.d("MainAction", "Find Filter");
filter = (Spinner) findViewById(R.id.filter);
Log.d("MainAction", "Create Adapter");
IconTextAdapter adapter = new IconTextAdapter();
Log.d("MainAction", "Create items");
for(int i=0; i<ETypes.names.length; i++){
IconText it = new IconText(ETypes.names[i], ETypes.icons[i]);
adapter.items.add(it);
}
Log.d("MainAction", "Setting adapter");
filter.setAdapter(adapter);
}
ETypes names[string] and icons[id] are static.
Inflator is initialized succesfully.
I haven't worked much in Android. If it were Java/Swing, I guess I would just call a redraw or something.
I know there are some bad practices here (all public variables, and so on). This code is still in early prototype stage, it will be fixed soon. I'm not looking for optimization, just for the solution to my problem.
Update 1:
So I saw I didn't implement getDropDownView so I did, the same code as getView (no need to post it?).
Also I made an experiment: At the end of IconText contrusctor I added
view = text
And it works just fine (showing only text).
I guess this pinpoints that the problem originates from custom view?
Update 2:
Did another experiment with IconText, setting view = icon; and it doesn't behave as it should, ie. it behaves like it's a custom view.
Doesn't really solve this specific bug, but it solves my problem.
Custom Image and Text View in Spinner Solution.
To update the list you must call
adapter.notifyDataSetChanged()
after adding new data to your adapter
Please refer to the following
https://developer.android.com/reference/android/widget/BaseAdapter.html#notifyDataSetChanged()

Dynamically adding view or inflating layout to RecyclerView's item

I am working on a social network application in which I need to show feeds to subscribers.. for showing feeds in a list. I am using RecyclerView. No Problem till now... but the problem comes when I have to show some comments on the feed. I am trying to accomplish a layout similar to Instagram where they show an image and maximum 3-4 comments with it in the main list. I am getting Image links and its comments (in JSON array form) from server.. sometimes I get comment array size 0 and sometime 1/2../10. I have created an XML for the comment layout that contains 2 TextView and I am inflating it in FeedViewHolder based on my ViewType.. my item_comment look like
<RelativeLayout
android:id="#+id/comment_layout"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="5dp"
android:paddingLeft="5dp"
android:paddingTop="5dp">
<TextView
android:textStyle="bold"
android:textColor="#color/indigo_500"
android:id="#+id/comment_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:src="#drawable/profile_pic"
android:text="Somesh Kumar"/>
<TextView
android:id="#+id/comment_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/comment_name"
android:ellipsize="end"
android:paddingLeft="5dp"
android:singleLine="true"
android:text="This is a comment"/>
</RelativeLayout>
I am passing my feed list to RecyclerView adaptor..and then I am checking if the item (that will be shown) should have the comments or not.
#Override
public int getItemViewType(int position)
{
FeedParser.DataClass dataClass = feedList.get(position);
int ITEM_TYPE = 0;
if (dataClass.getPost_type() == FEED_TYPE_PICTURE) // Feed item contains caption with pictures
{
// check if it has comments
if (dataClass.getComments().size() == 0)
{
ITEM_TYPE = PICTURE_WITHOUT_COMMENTS;
}
else
{
ITEM_TYPE = PICTURE_WITH_COMMENTS;
}
}
return ITEM_TYPE;
}
and passing ITEM_TYPE to onCreateViewHolder like
#Override
public FeedViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_feed, parent, false);
return new FeedViewHolder(itemView, viewType);
}
and in FeedViewHolder inflating item layout and comment layout if viewType has comments
public FeedViewHolder(View itemView, int viewType)
{
super(itemView);
tvFeedUsername = (TextView) itemView.findViewById(R.id.tvFeedUsername);
tvFeedCaption = (TextView) itemView.findViewById(R.id.tvFeedCaption);
switch (viewType)
{
// TODO: Write code for other feed type such as picture and video
// viewType 1 = PICTURE_WITH_COMMENTS
case 1:
layoutComments = (LinearLayout) itemView.findViewById(R.id.layoutComments);
commentView = layoutInflater.inflate(R.layout.item_comment, null);
postCommentText = (TextView) commentView.findViewById(R.id.comment_text);
postCommentName = (TextView) commentView.findViewById(R.id.comment_name);
layoutComments.addView(commentView);
break;
}
}
I have verified this works perfect but when i setText for holder.postCommentName & holder.postCommentText in onBindViewHolder it only set text for last comment ( i know it's because i am looping through all the comment and setting them one by one on the same holder.postCommentText and holder.postCommentName here is my onBindViewHolder..
#Override
public void onBindViewHolder(FeedViewHolder holder, int position)
{
FeedParser.DataClass feedModel = feedList.get(position);
holder.tvFeedUsername.setText(feedModel.getName());
holder.tvFeedCaption.setText(feedModel.getPost_status());
if (getItemViewType(position) == TEXT_WITH_COMMENTS)
{
for (int commentNum = 0; commentNum < feedModel.getComments().size(); commentNum++)
{
holder.postCommentName.setText(feedModel.getComments().get(commentNum).getUser_name());
holder.postCommentText.setText(feedModel.getComments().get(commentNum).getComment());
}
}
}
I don't know even if this is the right approach or not... but this is how some people wrote an answer here... like This one . I have searched many SO post but not getting what I want. Is there any other way where I can inflate comment's XML layout and add it multiple time on RecyclerView 's item?
Thanks any help would be much appreciated!
i Believe you need to create a nested recycler view in the main recycler view and you need to pass the data into the nested adapter as that of the comments .So basically
1.)Main Recycler View contains Caption , Image , RecyclerView for comments (as per instagram)
2.)In the second reyclerview put your above comment layout and create a seperate adapter with data as comments
Thats It .. Ask me for any further help

UniversalImageLoader crash (while scrolling wild up and down)

I am having crashes in a gridview using NOSTRAs UniversalImageLoader. There are around 1.5k images in the list to scroll through. But i guess its not related the bitmaps themself in the memory, but its related to too many thread creations. Basically i am scrolling up and down and up and down very wild. And i guess there are too many thread created and i am seeing this in the log very often
D/dalvikvm: create interp thread : stack size=32KB
D/dalvikvm: create new thread
D/dalvikvm: new thread created
D/dalvikvm: update thread list
and eventually i see
E/dalvikvm: Thread creation failed (err=Invalid argument, stacksize=1085584KB)
A/libc: Fatal signal 7 (SIGBUS) at 0x84849142 (code=1), thread 28383 (nomad5.beatsnap)
or sometimes this
E/dalvikvm: Thread creation failed (err=Invalid argument, stacksize=1085584KB)
A/libc: Fatal signal 11 (SIGSEGV) at 0x84849142 (code=2), thread 14546 (nomad5.beatsnap)
sometimes is paired with
java.lang.OutOfMemoryError: pthread_create (stack size 16384 bytes) failed: Try again
but sometimes this crash is not shown in the log. Here is my UIL config
.denyCacheImageMultipleSizesInMemory().diskCacheSize(64 * 1024 * 1024).threadPoolSize(5);
and here my display options
.bitmapConfig(Bitmap.Config.RGB_565)
.imageScaleType(ImageScaleType.IN_SAMPLE_INT)
.cacheInMemory(false).cacheOnDisk(true).showImageOnFail(R.drawable.ic_image_choose_error)
.showImageForEmptyUri(R.drawable.ic_image_choose_error)
I am loading images already in a very small size. Here is the loading call
ImageLoader.getInstance()
.displayImage("file://" + this.imageList.get(position),
new ImageViewAware(imageView),
this.options,
new ImageSize(100, 100),
new SimpleImageLoadingListener()
{
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage)
{
...
}
},
null);
By the way, my apps memory is constantly stable at around 40MB.
So as you see i disabled all the memory caching. I am also using large heap in the XML.
Any suggestions how to avoid this crashes? Is there a way to limit the thread creation counts?
Update #1
I have tried it with loadImage and removed all other code. Its still happening.
Here is my adapter code. The imageList is a list with ~1.5k entries. Just paths to the images on the phone.
public class ImageAdapter extends BaseAdapter
{
// all the paths
private final ArrayList<String> imageList;
// the layout inflater
private final LayoutInflater layoutInflater;
// checked array
private final SparseBooleanArray checkedArray = new SparseBooleanArray();
// options for loading into the grid
private final DisplayImageOptions options;
/**
* Constructor to use
*/
public ImageAdapter(#NonNull Context context,
#NonNull ArrayList<String> imageList)
{
// init members
this.layoutInflater = LayoutInflater.from(context);
this.imageList = imageList;
// image options
this.options = new DisplayImageOptions.Builder().bitmapConfig(Bitmap.Config.RGB_565)
.imageScaleType(ImageScaleType.IN_SAMPLE_INT)
.cacheInMemory(false)
.cacheOnDisk(true)
.showImageOnFail(R.drawable.ic_image_choose_error)
.showImageForEmptyUri(R.drawable.ic_image_choose_error)
.imageScaleType(ImageScaleType.EXACTLY)
.build();
}
#Override
public int getCount()
{
return this.imageList.size();
}
#Override
public Object getItem(int position)
{
return null;
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
if(convertView == null)
{
convertView = this.layoutInflater.inflate(R.layout.fragment_image_choose_element, null);
}
convertView.setTag(position);
// load the image
final View finalConvertView = convertView;
ImageLoader.getInstance()
.loadImage("file://" + this.imageList.get(position),
new ImageSize(100, 100),
this.options,
null);
return convertView;
}
}
and here is the file fragment_image_choose_element.xml that is inflated in the getView method:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id = "#+id/image_choose_element"
xmlns:android = "http://schemas.android.com/apk/res/android"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_gravity = "center"
android:gravity = "center">
<ImageView
android:id = "#+id/image_choose_element_image"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:adjustViewBounds = "false"
android:scaleType = "centerCrop"/>
</RelativeLayout>

Finding out the parent of clicked element in android ListView

I'm building my first app based on material from http://javatechig.com/video/json-feed-reader-in-android.
Everything goes ok so far, but I found one bug with ListView elements, which I can not manage to resolve by myself :(
I have extended list_row_layout.xml by 2 fields:
<Button
android:layout_width="wrap_content"
android:layout_height="20dp"
android:text="komcie"
android:textSize="11sp"
android:id="#+id/loadComments"
android:layout_gravity="center|bottom"
android:background="#bbb"
android:layout_marginLeft="5dp"
android:enabled="true"
android:clickable="true"
android:onClick="clickedLoadComments"
android:elegantTextHeight="true"
android:layout_toRightOf="#id/thumbImage"
android:layout_below="#+id/content"
android:padding="1px" />
<ListView
android:id="#+id/comment_list"
android:layout_toRightOf="#id/thumbImage"
android:layout_below="#+id/content"
android:paddingTop="5dp"
android:layout_marginTop="0dp"
android:paddingLeft="5dp"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:cacheColorHint="#00000000"
android:dividerHeight="1dp"
android:focusable="false"
android:listSelector="#drawable/list_selector_flatcolor"
android:visibility="invisible" />
Button.android:onClick="clickedLoadComments" function load Json with elements into ListView/comment_list. It works quite fine. But if there are more elements than could be displayed on screen (~8 elements) there is a bug. Comments from clicked element are loaded into every 8th element in a ListView.
Some code:
public void clickedLoadComments(View v)
{
try {
View parent = (View)v.getParent();
ViewHolder t = (ViewHolder) parent.getTag();
if( parent != null ) {
this.loadCommentsForLeaf(parent);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
protected void loadCommentsForLeaf( View view )
{
String tmpUrl = "http://some.url.com/Ajax/LoadComments?lid=" + this.currentLeafInUse;
JSONObject commentsJson = this.getJSONFromUrl(tmpUrl);
this.parseJsonComments(commentsJson);
if( commentsJson != null )
this.updateCommentList(view);
}
public void updateCommentList( View view) {
commentListView = (ListView) view.findViewById(R.id.comment_list);
commentListView.setVisibility(View.VISIBLE);
CommentListAdapter cla = new CommentListAdapter(this, this.commentList.get(this.currentLeafInUse));
commentListView.setAdapter(cla);
// Set list height.
ViewGroup.LayoutParams params = commentListView.getLayoutParams();
params.height = setListViewHeightBasedOnItems(commentListView) + 20;
commentListView.setLayoutParams(params);
commentListView.requestLayout();
}
CustomListAdapter.java code is mostly the same as the one in tutorial.
I would really appreciate help as I have spent many hours figuring it out with not success :(
This is just a guess. You might post your Adapter code and your parseJsonComments also if this does not work.
The Cause:
The problem you are describing might be caused due to the recycling and the reusage of Views. Take a look at this image from http://android.amberfog.com
As you can see the 1. items is reused and becomes the 8. item after scrolling.
Let's assume that Item 1 has an OnClickListener which updates a Text of the item.
For example we set the text to "clicked" after the OnClickListener is triggered.
Because item 1 is reused to create item 8, item 8 will also display the text "clicked".
The Solution:
The usual way is to save all states/content in a List(or whatever) and update everything in the getView call. So if you want to update text:
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
...
holder.textView.setText(jsonTexts[position]);
...
return convertView;
}
And if you want to update an item just update the List in your Adapter which holds the content/JsonObjects(etc.) and call notifyDataSetChanged.
public void updateCommentList(JSONObject commentsJson, int position) {
// does not exist you might create something
//like that in your Adapter class
commentListAdapter.updateItem(commentsJson,position);
commentListAdapter.notifyDataSetChanged();
}
After i populate the listview i call this method:
private void registerClickCallback() {
ListView list = (ListView) findViewById(R.id.lv);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked,
int position, long id) {
String xx = position+ ":" + id;
//then you can do what ever you want
}
});
}

Cannot display image correctly using custom item layout in ListView

I am using a ListView to display my custom item layout, which may contain some TextViews and an ImageView.
This is the item layout I made (post_item.xml):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="60dip"
android:padding="5dip"
>
<TextView android:id="#+id/listItem_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_weight="1"
/>
<FrameLayout android:id="#+id/listItem_frameContent"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#id/userStream_listItem_title"
android:layout_weight="1"
>
</FrameLayout>
</RelativeLayout>
I don't put the ImageView initially in the xml layout, but I will insert it when I need to the FrameLayout programmatically (I also put another views in it when needed). So, there will be some items which has ImageView in it and which don't.
I get the image to fill the ImageView from the Internet (through URL), decode it as Bitmap, and keep it as a Bitmap variable in a class represents the custom item layout (class PostItem).
When the activity shows for the first time it looks fine, but as I scrolled through the items then a problem showed up, the items which shouldn't show any image show the image from the other item which should, although they don't have any ImageView (because I didn't insert it).
I am using SDK 1.6 and the emulator. Haven't tried it in real device because I don't have it.
Here is my code for the Adapter:
private class PostItemAdapter extends ArrayAdapter<PostItem> {
private List<PostItem> mPostItems;
public PostItemAdapter(Context context, int textViewResourceId, List<PostItem> postItems) {
super(context, textViewResourceId, postItems);
mPostItems = postItems;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater layoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.post_item, null);
}
PostItem postItem = mPostItems.get(position);
if (postItem != null) {
final FrameLayout contentFrame = (FrameLayout) view.findViewById(R.id.listItem_frameContent);
final TextView titleTextView = (TextView) view.findViewById(R.id.listItem_title);
if (titleTextView != null) {
titleTextView.setText(postItem.getTitle());
}
if (contentFrame != null) {
if (postItem.hasImagePreview()) {
final ImageView previewImageView = new ImageView(getApplicationContext());
previewImageView.setId(LIST_ITEM_IMAGEVIEW_ID);
previewImageView.setAdjustViewBounds(true);
previewImageView.setMaxHeight(75);
previewImageView.setMaxWidth(75);
previewImageView.setImageBitmap(postItem.getImagePreview());
final RelativeLayout.LayoutParams layoutParams =
new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
contentFrame.addView(previewImageView, layoutParams);
}
if (postItem.hasContent()) {
final TextView contentTextView = new TextView(getApplicationContext());
contentTextView.setText(postItem.getContent());
final RelativeLayout.LayoutParams layoutParams =
new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.BELOW, LIST_ITEM_IMAGEVIEW_ID);
layoutParams.addRule(RelativeLayout.ALIGN_LEFT, LIST_ITEM_IMAGEVIEW_ID);
layoutParams.alignWithParent = true;
contentFrame.addView(contentTextView, layoutParams);
}
}
}
return view;
}
}
And this is the code to prepare the items:
/* inside a method to prepare the items */
mPostItems = new ArrayList<PostItem>();
for (int i=0; i<total); i++) {
/* operation to generate titleToDisplay and contentToDisplay */
/* contentToDisplay might be null */
mPostItems.add(new PostItem(
titleToDisplay,
contentToDisplay,
generateImagePreview()));
}
/* another method */
private Bitmap generateImagePreview(ActivityObject object) {
Bitmap imagePreview = null;
if (/*some condition*/) {
try {
InputStream inStream = (InputStream) (new URL("http://a1.typepad.com/6a010535617444970b0133ecc20b29970b-120si")).getContent();
imagePreview = Drawable.createFromStream(inStream, "linkHref");
}
catch (MalformedURLException ex) {
Log.e("INSIDE generateImagePreview()", ex.getMessage());
}
catch (IOException ex) {
Log.e("INSIDE generateImagePreview()", ex.getMessage());
}
catch (Exception ex) {
Log.e("INSIDE generateImagePreview()", ex.getMessage());
}
}
return imagePreview;
}
Is this the bug in the emulator or there is some mistake in my code (probably memory problem for the Bitmap)? Please help me, I'm really stuck in this. Any help or advice will be very appreciated. Thanks in advance :)
Cells get reused by lists and it looks like you are only altering your contentframe image if there is an image associated with the item. This means when there is no image and you are reusing a cell, it will just show whatever was passed in in the convert view. If there is no image then you should remove all children views of contentframe.
That said, you will likely get better responses in the future by being more concise. Putting up a bunch of code and taking a while to get to the issue makes it more of a chore to read and so fewer people will.

Categories

Resources