in the recycle view, I'm loading data by this query it's loading fine. But after scrolling down it's getting scattered.
Query query = db.collection(USER_MASTER_KEY)
.document(Uid)
.collection("following")
.document(xpertId)
.collection("chat_transcript")
.orderBy(TIMESTAMP_KEY);
here is my onBind method.here i'm loading image, text , video at the same time.I build this recycler in a chatting bot app.where response of the data is previously loaded in the firebase. According to the qustion the ans will be loaded.everything loading currectly but after two three video loading problem occuring.
#Override
public void onBindViewHolder(#NonNull final ChatViewHolder holder, int position) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
final ChatViewData chatViewData1 = chatViewDataList.get(position);
klog.d("## CHAT ITEM-", new Gson().toJson(chatViewData1));
String chatData = chatViewData1.getMsgContent();
// If the message is still pending show placeholder
if (chatViewData1.MSG_TYPE_PACEHOLDER.equalsIgnoreCase(chatViewData1.getMsgType())) {
holder.gifImageViewLoading.setVisibility(VISIBLE);
holder.leftMsgTextView.setVisibility(GONE);
holder.rightMsgTextView.setVisibility(GONE);
holder.leftImageView.setVisibility(GONE);
holder.relativeLayout.setVisibility(GONE);
}
// If the message type is blank, show nothing
if (chatViewData1.getMsgType().equalsIgnoreCase("")) {
holder.gifImageViewLoading.setVisibility(GONE);
holder.leftMsgTextView.setVisibility(GONE);
holder.rightMsgTextView.setVisibility(GONE);
holder.leftImageView.setVisibility(GONE);
holder.relativeLayout.setVisibility(GONE);
}
// If the message is a received message.
if (chatViewData1.MSG_TYPE_RECEIVED.equals(chatViewData1.getMsgType())) {
holder.leftMsgTextView.setText(HtmlCompat.fromHtml(chatData, HtmlCompat.FROM_HTML_MODE_COMPACT), TextView.BufferType.SPANNABLE);
holder.gifImageViewLoading.setVisibility(GONE);
holder.leftMsgTextView.setVisibility(VISIBLE);
//holder.chatLikeOption.setVisibility(VISIBLE);
//holder.chatDislikeOption.setVisibility(VISIBLE);
holder.rightMsgTextView.setVisibility(GONE);
holder.leftImageView.setVisibility(GONE);
holder.relativeLayout.setVisibility(GONE);
}
// If the message is a sent message.
else if (chatViewData1.MSG_TYPE_SENT.equals(chatViewData1.getMsgType())) {
holder.rightMsgTextView.setText(HtmlCompat.fromHtml(chatData, HtmlCompat.FROM_HTML_MODE_COMPACT), TextView.BufferType.SPANNABLE);
holder.gifImageViewLoading.setVisibility(GONE);
holder.rightMsgTextView.setVisibility(VISIBLE);
holder.leftMsgTextView.setVisibility(GONE);
holder.leftImageView.setVisibility(GONE);
holder.relativeLayout.setVisibility(GONE);
}
// If the message is an image message.
else if (chatViewData1.MSG_TYPE_IMAGE.equals(chatViewData1.getMsgType())) {
//Load Image using Picasso library
Picasso.get().load(chatViewData1.getMsgContent()).into(holder.leftImageView);
holder.gifImageViewLoading.setVisibility(GONE);
holder.leftImageView.setVisibility(VISIBLE);
holder.rightMsgTextView.setVisibility(GONE);
holder.leftMsgTextView.setVisibility(GONE);
holder.relativeLayout.setVisibility(GONE);
}
// If the message is a video message.
else if (chatViewData1.MSG_TYPE_VIDEO.equals(chatViewData1.getMsgType())) {
final String videoId = chatViewData1.getMsgContent();
final ImageView yimageView = holder.YoutubeImageView;
final String url = "https://img.youtube.com/vi/" + videoId + "/default.jpg";
BitmapFactory.Options bmOptions;
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
Bitmap bm = loadBitmap(url, bmOptions);
yimageView.setVisibility(VISIBLE);
//holder.videoLikeOption.setVisibility(VISIBLE);
//holder.videoDislikeOption.setVisibility(VISIBLE);
yimageView.setImageBitmap(bm);
yimageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent("custom-message");
// intent.putExtra("quantity",Integer.parseInt(quantity.getText().toString()));
intent.putExtra("startTime", chatViewData1.getStartSeconds());
intent.putExtra("endTime", chatViewData1.getEndSeconds());
intent.putExtra("videoId", videoId);
LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);
}
});
}
}
Use this two method on adpter of recycleview
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
Related
The app I am making need to take pictures to send them to a server.
I need to take 6 photos at least. I have a recyclerView in which I am displaying a preview of my photo. It's working perfectly (I am using Picasso as photo library).
I need to be able to delete photos before sending them away (and consequently their preview). With a click on the preview, I remove it from my photo tab and update my recyclerview with notifyDataSetChanged().
The photo disappears.
When I take an other picture, I have its preview but the preview from the deleted picture is coming back.
If I delete three pictures and take a new one, I have the preview of the new one and the preview of the 3 deleted pictures.
Here's part of my adapter where I bind my view
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
mImageView = holder.mPhotoIV;
File mFile = new File(String.valueOf(Uri.parse(mListOfPhotos.get(position))));
int width = mImageView.getLayoutParams().width;
int height = mImageView.getLayoutParams().height;
Picasso.get()
.load(mFile)
.resize(200, 200)
.error(R.drawable.ic_no_photo_foreground)
.into(mImageView, new com.squareup.picasso.Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError(Exception e) {
}
});
}
Here part of my activity where I'm calling my adapter
mTakePhotoFAB.setOnClickListener(view -> {
mDir = new File(getExternalCacheDir(), "PhotosAuthentifier");
boolean success = true;
if (!mDir.exists()) {
success = mDir.mkdir();
}
if (success) {
File mFile = new File(mDir, new SimpleDateFormat("yyyyMMdd-HHmmss", Locale.getDefault()).format(new Date()) + ".jpg");
mImageCapture.takePicture(mFile,
new ImageCapture.OnImageSavedListener() {
#Override
public void onImageSaved(#NonNull File file) {
mListOfPhotos.add(file.getAbsolutePath());
mNumberOfPhotoTV.setText(getResources().getString(R.string.minPhotos, mListOfPhotos.size()));
if (mListOfPhotos.size() >= 6) {
mSendPhotoFAB.setVisibility(View.VISIBLE);
}
mAdapter = new CameraPhotoAdapter(mListOfPhotos, getBaseContext());
mRecyclerView.setAdapter(mAdapter);
}
#Override
public void onError(#NonNull ImageCapture.ImageCaptureError imageCaptureError, #NonNull String message, #Nullable Throwable cause) {
String mMessage = "Photo capture failed: " + message;
Toast.makeText(CameraActivity.this, mMessage, Toast.LENGTH_SHORT).show();
assert cause != null;
cause.printStackTrace();
}
});
}
});
Function (in my adapter) to remove picture
protected void removePhoto(Context context, ArrayList<String> array, int position) {
File mDir = new File(context.getExternalCacheDir(), "PhotosAuthentifier");
File mFile = new File(array.get(position));
if (mDir.exists()) {
File[] mFilesIntoDir = mDir.listFiles();
if (mFilesIntoDir == null) {
return;
} else {
for (int i = 0; i < mFilesIntoDir.length; i++) {
if (mFilesIntoDir[i].getAbsolutePath().equals(mFile.getAbsolutePath())) {
boolean mSuccess = mFilesIntoDir[i].delete();
if (mSuccess) {
Picasso.get().invalidate(mFile.getAbsolutePath());
mListOfPhotos.remove(mFile.getAbsolutePath());
notifyDataSetChanged();
}
}
}
}
}
}
I tried to invalidate Picasso cache but when I take a new picture, instead of the deleted picture reappearing I have the default behavior when I don't have a good url to upload (a black cross)
Could anyone help please :)?
P.S. the big chat bubbles at the bottom of the screen are an image (just like when you send an image via WhatsApp and other messaging apps)
I'm making a simple chatting app. The problem is, whenever I scroll to the top, the view comes back to the very bottom. Here's my OnBindViewHolder code (some parts are omitted because it's too long):
#Override
public void onBindViewHolder(final MessageViewHolder viewHolder, final int i) {
final ChatMessages c = messageList.get(i);
final String from_user = c.getFrom();
String message_type = c.getType();
if (currentUser.equals(from_user)) {
viewHolder.mydisplayName.setText(dummyright);
} else {
viewHolder.displayName.setText(dummyleft);
}
if (currentUser.equals(from_user)) {
leftLayout.setVisibility(View.VISIBLE);
rightLayout.setVisibility(View.GONE);
person = "leftLayout";
} else {
leftLayout.setVisibility(View.GONE);
rightLayout.setVisibility(View.VISIBLE);
person = "rightLayout";
}
if (message_type.equals("text")) {
//set visibility of TextViews and other elements according to which user is sending the message (left/right)
} else if (message_type.equals("image")) {
if (person.equals("leftLayout")) {
viewHolder.mymessageText.setVisibility(View.GONE);
viewHolder.myview_data.setVisibility(View.GONE);
viewHolder.mymessageImage.setVisibility(View.VISIBLE);
Cursor cursor = null;
final String tempUri = c.getDownload_link();
filename = null;
byte[] decodedString = Base64.decode(c.getMessage(), Base64.DEFAULT);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
options.inPreferredConfig = Bitmap.Config.RGB_565;
options.inSampleSize=512;
decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length,options);
try {
Glide.with(viewHolder.mymessageImage.getContext())
.asBitmap()
.load(decodedString)
.thumbnail(0.5f)
.into(viewHolder.mymessageImage);
decodedString=null;
} catch (Exception e) {
Log.e("chat image right", e.getMessage());
}
File file = null;
if (tempUri != null) {
file = new File(tempUri);
String path = file.getAbsolutePath();
if (tempUri.startsWith("content://")) {
try {
cursor = context.getContentResolver().query(Uri.parse(c.getDownload_link()), null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
filename = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
} finally {
cursor.close();
}
} else if (tempUri.startsWith("file://")) {
filename = file.getName();
}
viewHolder.mymessageImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = new AlertDialog.Builder(context, android.R.style.Theme_Material_Light_Dialog_Alert);
} else {
builder = new AlertDialog.Builder(context);
}
builder.setTitle("Save Image")
.setMessage("Do you want to save this image?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
startSaveImageToGallery();
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
});
} else {
}
} else if (person.equals("rightLayout")) {
//same as above but for the right layout
}
}
}
I've read a lot of questions about this issue and some of the answers said that it's caused by setting visibility inside onBindViewHolder. I don't know where else I would set them because my layouts' visibility are dependent on some data (in this case, who's sending the chats).
Edit: I've just tried my app several times and apparently it only jumps to the bottom when there are pictures being sent, especially when they're 600KB or more in size. I'm loading my images with Glide, they are stored in Base64 and converted to compressed Bitmaps. Do these images cause the messed up scrolling?
1.If the ImageView is wrap_content,set a fixed size value for it.
2.If the OnBindViewHolder method has other asyn operations which are relatived to the UI,deal with them before setData.
3.Check your code,if there are methods such as scroll to
I'm trying to use the library to perform volley download images from my server.
In my activity I add items dynamically and then realize the exchange of image at runtime.
Below is the code of the attempt to get the picture:
public void updateThumbnails(ArrayList<Book> arrBook,ArrayList<View> arrView){
if(arrBook.size()<= 0){
return;
}
if(arrView.size() <= 0){
return;
}
int intBooks = arrView.size();
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
for(int intIndex = 0; intIndex < intBooks; intIndex++){
View _view = arrView.get(intIndex);
final View _viewLoader = _view;
imageLoader.get(Const.START_REQUEST_BOOK_IMAGE + arrBook.get(intIndex).getId().toString() + ".jpg", new ImageLoader.ImageListener() {
#Override
public void onResponse(ImageLoader.ImageContainer imageContainer, boolean b) {
ImageView imgBook = (ImageView) _viewLoader.findViewById(R.id.img_book);
animationChangeImage(imageContainer.getBitmap(),imgBook);
}
#Override
public void onErrorResponse(VolleyError volleyError) {
}
});
TextView txtTitleBook = (TextView) _view.findViewById(R.id.name_book);
txtTitleBook.setVisibility(View.INVISIBLE);
}
}
You need to check that the returned bitmap (imageContainer.getBitmap()) isn't null before going ahead and assigning it.
Try and adding log prints to see if you're getting errors or a null bitmap, which could mean you're performing a bad request or server error, or perhaps the fault is in the animationChangeImage method if the bitmap is received successfully.
Did you try using the ImageRequest class? For example:
ImageRequest irq = new ImageRequest(imgUrl, new Response.Listener<Bitmap>() {
#Override
public void onResponse(Bitmap response) {
imView.setImageBitmap(response);
}
}, 0, 0, null, null);
Hi i did one application here i need to share my score on twiter,i did using below code my score is posing fine,but now i need to share score along with app icon.but i dont know how to share that image along with text can any one help me,thankyou
TestPost.class:
public class TestPost extends Activity {
String review;
private TwitterApp mTwitter;
private String username = "";
private boolean postToTwitter = false;
private static final String twitter_consumer_key = "";
private static final String twitter_secret_key = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.post);
Button postBtn = (Button) findViewById(R.id.button1);
final EditText reviewEdit = (EditText) findViewById(R.id.revieew);
postBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
review = reviewEdit.getText().toString();
postToTwitter = true;
onTwitterClick();
}
});
mTwitter = new TwitterApp(this, twitter_consumer_key,twitter_secret_key);
mTwitter.setListener(mTwLoginDialogListener);
if (mTwitter.hasAccessToken()) {
username = mTwitter.getUsername();
username = (username.equals("")) ? "No Name" : username;
}
}
private void postToTwitter(final String review) {
new Thread() {
#Override
public void run() {
int what = 0;
try {
mTwitter.updateStatus(review);
} catch (Exception e) {
what = 1;
}
mHandler.sendMessage(mHandler.obtainMessage(what));
}
}.start();
}
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
String text = (msg.what == 0) ? "Posted to Twitter" : "Post to Twitter failed";
Toast.makeText(TestPost.this, text, Toast.LENGTH_SHORT).show();
}
};
private final TwDialogListener mTwLoginDialogListener = new TwDialogListener() {
#Override
public void onComplete(String value) {
username = mTwitter.getUsername();
username = (username.equals("")) ? "No Name" : username;
postToTwitter = true;
postToTwitter(review);
Toast.makeText(TestPost.this, "Connected to Twitter as " + username, Toast.LENGTH_LONG).show();
}
#Override
public void onError(String value) {
Toast.makeText(TestPost.this, "Twitter connection failed", Toast.LENGTH_LONG).show();
}
};
private void onTwitterClick() {
if (mTwitter.hasAccessToken()) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Delete current Twitter connection?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mTwitter.resetAccessToken();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
} else {
mTwitter.authorize();
}
}
}
This is how I upload an Image along with text to the logged in Twitter User's account. I make use of the TwitPic API for that. You will have to login and register a developer account there.
The solution can be thought of as a two step solution.
First, when the user clicks the post button, I first grab the Image and upload to TwitPic. From there, I grab the URL that is returned by TwitPic (String url = upload.upload(finalFile);).
In step two of this code, in a String instance (String finalStatusWithURL), I grab the content of an EditText and then append the URL from step 1 to it. With this done, the post is finally posted to Twitter.
Configuration conf = new ConfigurationBuilder()
.setOAuthConsumerKey(TWITTER_CONSUMER_KEY)
.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET)
.setOAuthAccessToken(twit_access_token)
.setOAuthAccessTokenSecret(twit_access_token_secret)
.setMediaProviderAPIKey(TWIT_PIC_API)
.build();
// SET THE FILE PATH
File finalFile = new File(getRealPathFromURI(initialURI));
// THIS IS IMPORTANT. TWITPIC NEEDS THE ACTUAL PATH ON THE DEVICE. JUST THE URI DOES NOT WORK!!!!
ImageUpload upload = new ImageUploadFactory(conf).getInstance(MediaProvider.TWITPIC);
String url = upload.upload(finalFile);
Log.e("TWITTER URL RESPONSE", url);
// NOW, UPLOAD TO TWITTER
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(YOUR_TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(YOUR_TWITTER_CONSUMER_SECRET);
AccessToken accessToken = new AccessToken(your_twit_access_token, your_twit_access_token_secret);
Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
String finalStatusWithURL = null;
if (finalStatusMessage.trim().length() > 0) {
finalStatusMessage = editStatusUpdate.getText().toString();
finalStatusWithURL = finalStatusMessage + ":\n " + url;
} else {
finalStatusWithURL = url;
}
twitter4j.Status response = twitter.updateStatus(finalStatusWithURL);
Log.e("TWITTER RESPONSE", response.getText());
This is a method to get the real path of the image you want to upload:
// HELPER METHOD TO GET REAL PATH FOR THE SELECTED IMAGE
public String getRealPathFromURI(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
Hope this helps. This is production code from an app of mine.
UPDATED:
Change this in the code:
File finalFile = new File(getRealPathFromURI(initialURI));
To this:
Uri tempUri = getImageUri(getApplicationContext(), icon);
File finalFile = new File(getRealPathFromURI(tempUri));
And the helper method for Uri tempUri = getImageUri(getApplicationContext(), bmpFinal);:
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
You will still need to pass a Bitmap object. To convert your app icon to a Bitmap, use this:
Bitmap icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher);
UPDATED 2:
A little while after you asking and me answering your question, Twitter wrapped up a developer meet in SF. They have introduced a few new Cards which I think may be of use to your specific use-case. It is fresh off the block and I haven't gotten around to testing/using it. But if it fits your purpose, take a look at these links:
http://www.engadget.com/2013/04/02/twitter-cards-apps-products-photo-galleries/ (Where I found out about the new feature)
https://dev.twitter.com/blog/mobile-app-deep-linking-and-new-cards (The official Twitter blog)
https://dev.twitter.com/cards (Developer page for details of the features and how to use them)
I know this is asked before and I have already searched a lot about this but could not get any proper answer on my issue.
I have created a list, the list gets filled with data that is coming from JSON. Now inside getView() method, I am inflating my custom row with data. Each row contains a Thumbnail, and I am creating each thumbnail from a different thread.
Now the problem is, everything is going well until I don't scroll my list. When I scroll my list, my getView() method is called continuously , and all thumbnail images are getting recreated and its position is getting shuffled. Once thumbnails are created I don't want to recreate them and also I want to maintain the order of my thumbnails.
Can you please guys help me on this?
Any help will greatly be appreciated.
My getView() method is:
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
ViewHolder viewHolder = new ViewHolder();
if (convertView == null) {
inflater = getLayoutInflater();
convertView = inflater.inflate(R.layout.list_item_row, parent,
false);
viewHolder.titleText = (TextView) convertView
.findViewById(R.id.titleText);
viewHolder.thumbImage = (ImageView) convertView
.findViewById(R.id.thumbnail);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
final String thumbnailURLString = mPostsList.get(position).get(
"thumb");
createBitmapThread = (Thread) getLastNonConfigurationInstance();
createBitmapThread = new MyThread(thumbnailURLString,
viewHolder.thumbImage);
createBitmapThread.start();
viewHolder.titleText.setText(title);
return convertView;
}
And the Thread class:
public class MyThread extends Thread {
String mThumbURLString = null;
ImageView mImageView = null;
public MyThread(String thumbnailURLString, ImageView imageView) {
mThumbURLString = thumbnailURLString;
mImageView = imageView;
}
#Override
public void run() {
try {
URL newurl = null;
try {
newurl = new URL(mThumbURLString);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
// Options opts = new Options();
/*
* opts.inDither = true; opts.inInputShareable = true;
* opts.inJustDecodeBounds = true; opts.inPurgeable =
* true;
*/
Log.e("", "INSIDE IMAGE DOINBG");
mBitmap = BitmapFactory
.decodeStream((InputStream) newurl.getContent());
} catch (IOException e) {
e.printStackTrace();
}
mHandler.post(new MyRunnable(mImageView));
} finally {
}
}
public class MyRunnable implements Runnable {
ImageView mImageView = null;
public MyRunnable(ImageView imageView) {
mImageView = imageView;
}
public void run() {
mImageView.setImageBitmap(mBitmap);
}
}
ok , here how i did a similar thing:
for each getView , create a new Fetching class and put it into a concurrent/synchronized stack . in the meanwhile , set the bitmap of the view to be empty (or anything else you wish) . you can also use caching instead.
the class will contain info of how to load the data (for example , the url of the bitmap) , the view to update , and the result of the fetching (for example , the bitmap itself) .
now , back to the getView, create&execute an asyncTask that will use a loop on the stack , each time it gets a Fetching class instance from the stack (once it's empty,the asyncTask will break the loop and finish) , check that the view that needs to be updated still needs the data (using its viewHolder) load the bitmap , set the result into the Fetching class , and pass it through the publishProgress() function.
in the onProgressUpdate method , do the same check as before using the Fetching class instance and the viewHolder . if all went well , update the view to have the bitmap that was fetched .
a nice yet complicated example of how to handle the same problem can be found here .
I was having the same problem and the suggestion above worked perfectly, finally - thanks! Code snippets below:
My AsyncTask:
protected class LoadImageTask extends AsyncTask<String, Void, String> {
private View v;
public LoadImageTask(View v) {
super();
this.v = v;
}
#Override
protected void onPostExecute(String result) {
Log.d(TAG, "<onPostExecute> load image complete. ");
}
#Override
protected String doInBackground(String... addresses) {
String response = "";
Bitmap bm = null;
for (String address : addresses) {
ViewHolder holder = (ViewHolder) v.getTag();
String name = getNameFromMDN(address);
if (name != null && name.length() > 0) {
// get contact ID from name
long id = getContactID(name);
if (id != 0) {
bm = getThumbnailForId(id);
if (bm != null && bm.getHeight() > 0) {
bm = resizeBitmap(bm);
holder.icon.setImageBitmap(bm);
Log.d(TAG, "set thumbnail for " + name + ", id: " + id);
}
}
}
// default icon
if (bm == null) {
Log.d(TAG, "using default icon for mdn: " + address + ", name: " + name);
holder.icon.setImageResource(R.drawable.contact_big);
/*String s = getContactNameByContactId(person, address);
s = s.substring(0, 2);
if (s.length() > 0 && !MDNUtil.isNumber(s)) {
Log.d(TAG, "using dynamic icon for person: " + person + ", mdn: " + address + ", name: " + s);
icon.setBackgroundColor(Color.BLUE);
iconText.setText(s);
iconText.setTextColor(Color.WHITE);
iconText.setVisibility(View.VISIBLE);
} else {
// use generic icon
holder.icon.setImageResource(R.drawable.contact_big);
}*/
}
}
return "";
}
then in the bindVew() of my CustomCursorAdapter:
LoadImageTask load = new LoadImageTask(v);
load.doInBackground(address);
update: what FINALLY WORKED was preventing the recycling of the views in the listview, in my custom cursor adapter:
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getViewTypeCount() {
return 500;
}