Hi in the below I am displaying images from sdcard.sdcard means storing into locally.but while privew the images it was showing some black color after image got displaying.
want to display smooth preview with black screen.i am unable to figure out the issue.can any one help me.
java
public class ImageGallery extends Activity {
Bundle bundle;
String catid, temp, responseJson;
JSONObject json;
ImageView imageViewPager;
// for parsing
JSONObject o1, o2;
JSONArray a1, a2;
int k;
Boolean toggleTopBar;
ArrayList<String> imageThumbnails;
ArrayList<String> imageFull;
public static int imagePosition=0;
SubsamplingScaleImageView imageView, imageViewPreview, fullImage ;
ImageView thumb1, back;
private LinearLayout thumb2;
RelativeLayout topLayout, stripeView;
RelativeLayout thumbnailButtons;
FrameLayout gridFrame;
//SharedPreferences data
SharedPreferences s1;
SharedPreferences.Editor editor;
int swipeCounter;
ParsingForFinalImages parsingObject;
int position_grid;
SharedPreferences p;
Bitmap bm;
int numOfImagesInsidee;
LinearLayout backLinLayout;
public static boolean isThumb2=false;
public static boolean isThumb1=false;
public static ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_gallery);
//isThumb2=false;
toggleTopBar = false;
//position_grid=getIntent().getExtras().getInt("position");
thumbnailButtons = (RelativeLayout)findViewById(R.id.thumbnailButtons);
topLayout = (RelativeLayout)findViewById(R.id.topLayout);
//fullImage = (SubsamplingScaleImageView)findViewById(R.id.fullimage);
backLinLayout = (LinearLayout)findViewById(R.id.lin_back);
backLinLayout.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent io = new Intent(getBaseContext(), MainActivity.class);
// clear the previous activity and start a new task
// System.gc();
// io.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(io);
finish();
}
});
ConnectionDetector cd = new ConnectionDetector(getBaseContext());
Boolean isInternetPresent = cd.isConnectingToInternet();
thumb1 = (ImageView)findViewById(R.id.thumb1);
thumb2 = (LinearLayout)findViewById(R.id.thumb2);
stripeView = (RelativeLayout)findViewById(R.id.stripeView) ;
gridFrame = (FrameLayout)findViewById(R.id.gridFrame);
thumb1.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
stripeView.setVisibility(View.GONE);
gridFrame.setVisibility(View.VISIBLE);
viewPager.setVisibility(View.GONE);
//fullImage.setVisibility(View.GONE);
thumb1.setClickable(false);
isThumb1=true;
isThumb2=false;
Log.i("Thumb Position 1",""+ImageGallery.imagePosition);
viewPager.removeAllViews();
Fragment newFragment = new GridFragment2();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.gridFrame, newFragment).commit();
}
});
thumb2.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
// stripeView.setVisibility(View.VISIBLE);
stripeView.setVisibility(View.GONE);
gridFrame.setVisibility(View.VISIBLE);
viewPager.setVisibility(View.GONE);
// fullImage.setVisibility(View.GONE);
thumb1.setClickable(true);
isThumb2=true;
isThumb1=false;
Log.i("Thumb Position 2",""+ImageGallery.imagePosition);
viewPager.removeAllViews();
Fragment newFragment = new ImageStripeFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.gridFrame, newFragment).commit();
}
});
// allow networking on main thread
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
/*bundle = getIntent().getExtras();
catid = bundle.getString("catid");*/
// Toast.makeText(getBaseContext(), catid, Toast.LENGTH_LONG).show();
// making json using the catalogue id we got
p = getSharedPreferences("gridData", Context.MODE_APPEND);
catid = p.getString("SelectedCatalogueIdFromGrid1", "");
int clickedListPos = p.getInt("clickedPosition", 0);
imageViewPreview = (SubsamplingScaleImageView)findViewById(R.id.preview);
imageThumbnails = new ArrayList<String>();
imageFull = new ArrayList<String>();
s1 = this.getSharedPreferences("data", Context.MODE_APPEND);
editor = s1.edit();
Log.d("catidfnl", catid);
numOfImagesInsidee = p.getInt("numberOfItemsSelectedFromGrid1", 0);
Log.d("blingbling2", String.valueOf(numOfImagesInsidee));
// adding downloaded images to arraylist
for(int m=0;m<numOfImagesInsidee;m++){
imageThumbnails.add(Environment.getExternalStorageDirectory()+"/"+"thumbImage" + catid + m+".png");
imageFull.add(Environment.getExternalStorageDirectory()+"/"+"fullImage" + catid + m+".png");
// imageFull.add("file://" + Environment.getExternalStorageDirectory() + "/" + "fullImage32.png");
}
viewPager = (ViewPager) findViewById(R.id.pager);
ImagePagerAdapter adapter = new ImagePagerAdapter();
viewPager.setAdapter(adapter);
// SubsamplingScaleImageView fullImage = new SubsamplingScaleImageView(ImageGallery.this);
// code to display image in a horizontal strip starts here
LinearLayout layout = (LinearLayout) findViewById(R.id.linear);
for (int i = 0; i < imageThumbnails.size(); i++) {
imageView = new SubsamplingScaleImageView(this);
imageView.setId(i);
imageView.setPadding(2, 2, 2, 2);
// Picasso.with(this).load("file://"+imageThumbnails.get(i)).into(imageView);
// imageView.setScaleType(ImageView.ScaleType.FIT_XY);
layout.addView(imageView);
ViewGroup.LayoutParams params = imageView.getLayoutParams();
params.width = 200;
params.height = 200;
imageView.setLayoutParams(params);
imageView.setZoomEnabled(false);
imageView.setDoubleTapZoomScale(0);
imageView.setImage(ImageSource.uri(imageThumbnails.get(0)));
imageView.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
imageView.setZoomEnabled(false);
imageViewPreview.setImage(ImageSource.uri(imageFull.get(view.getId())));
imageView.recycle();
imageViewPreview.recycle();
}
});
}
// code to display image in a horizontal strip ends here
imageViewPreview.setZoomEnabled(false);
/*imageViewPreview.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
imageViewPreview.setZoomEnabled(false);
stripeView.setVisibility(View.GONE);
gridFrame.setVisibility(View.GONE);
viewPager.setVisibility(View.VISIBLE);
}
});*/
imageViewPreview.setOnClickListener(new DoubleClickListener() {
#Override
public void onSingleClick(View v) {
Log.d("yo click", "single");
}
#Override
public void onDoubleClick(View v) {
Log.d("yo click", "double");
}
});
}
public abstract class DoubleClickListener implements View.OnClickListener {
private static final long DOUBLE_CLICK_TIME_DELTA = 300;//milliseconds
long lastClickTime = 0;
#Override
public void onClick(View v) {
long clickTime = System.currentTimeMillis();
if (clickTime - lastClickTime < DOUBLE_CLICK_TIME_DELTA){
onDoubleClick(v);
} else {
onSingleClick(v);
}
lastClickTime = clickTime;
}
public abstract void onSingleClick(View v);
public abstract void onDoubleClick(View v);
}
// #Override
// public void onBackPressed() {
// Intent io = new Intent(getBaseContext(), MainActivity.class);
// // clear the previous activity and start a new task
// super.onBackPressed();
// finish();
// // System.gc();
// // io.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
// startActivity(io);
// }
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_image_gallery, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class ImagePagerAdapter extends PagerAdapter {
/* private int[] mImages = new int[] {
R.drawable.scroll3,
R.drawable.scroll1,
R.drawable.scroll2,
R.drawable.scroll4
};*/
/* private String[] description=new String[]
{
"One","two","three","four"
};
*/
#Override
public int getCount() {
Log.i("Image List Size", "" + imageFull.size());
return imageFull.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((SubsamplingScaleImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = ImageGallery.this;
SubsamplingScaleImageView fullImage = new SubsamplingScaleImageView(ImageGallery.this);
// for placeholder
// fullImage.setImage(ImageSource.resource(R.drawable.tan2x));
if(!GridFragment2.isSelectedGrid2&&!ImageStripeFragment.isImageStripe) {
imagePosition = position;
fullImage.setImage(ImageSource.uri(imageFull.get(imagePosition)));
}
/* else if(!ImageStripeFragment.isImageStripe)
{
imagePosition = position;
fullImage.setImage(ImageSource.uri(imageFull.get(imagePosition)));
}
else if(ImageStripeFragment.isImageStripe)
{
position=imagePosition;
viewPager.setCurrentItem(imagePosition);
fullImage.setImage(ImageSource.uri(imageFull.get(position)));
}*/
else
{
position=imagePosition;
viewPager.setCurrentItem(imagePosition);
fullImage.setImage(ImageSource.uri(imageFull.get(position)));
//viewPager.removeAllViews();
}
// ImageView imageViewPager = new ImageView(context);
// ImageView imageViewPager = new ImageView(getApplicationContext());
// SubsamplingScaleImageView fullImage = new SubsamplingScaleImageView(ImageGallery.this);
GridFragment2.isSelectedGrid2=false;
ImageStripeFragment.isImageStripe=false;
// Log.i("Image Resource", "" + ImageSource.uri(imageFull.get(position)));
// imageViewPager.setImageBitmap(BitmapFactory.decodeFile(imageFull.get(position)));
// imageViewPager.setImageBitmap(myBitmap);
// fullImage.setImage(ImageSource.bitmap(bmImg));
//imageView.setImageResource(Integer.parseInt(imageFull.get(position)));
/*int padding = context.getResources().getDimensionPixelSize(
R.dimen.padding_medium);
imageView.setPadding(padding, padding, padding, padding);*/
/*imageView.setScaleType(ImageView.ScaleType.CENTER);
imageView.setImageResource(Integer.parseInt(imageFull.get(position)));
if(position==3)
{
}*/
// Log.i("Image Position",""+position);
/*text.setText(description[position]);
Log.i("Text Position",""+position);*/
/*switch(position)
{
case 0:
String pos=String.valueOf(position);
text.setText(pos);
break;
case 1:
String pos1=String.valueOf(position);
text.setText(pos1);
break;
case 2:
String pos2=String.valueOf(position);
text.setText(pos2);
break;
case 3:
String pos3=String.valueOf(position);
text.setText(pos3);
break;
}*/
fullImage.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
if (toggleTopBar == false) {
// thumbnailButtons.setVisibility(View.GONE);
thumbnailButtons.animate()
.translationY(-2000)
.setDuration(1000)
.start();
toggleTopBar = true;
} else if (toggleTopBar == true) {
// thumbnailButtons.setVisibility(View.VISIBLE);
thumbnailButtons.animate()
.translationY(0)
.setDuration(1000)
.start();
toggleTopBar = false;
}
}
});
((ViewPager) container).addView(fullImage, 0);
return fullImage;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((SubsamplingScaleImageView) object);
}
/* #Override
public void destroyItem(View collection, int position, Object o) {
Log.d("DESTROY", "destroying view at position " + position);
View view = (View) o;
((ViewPager) collection).removeView(view);
view = null;
}*/
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
use this ImageLoader Class
public class ImageLoader {
MemoryCache memoryCache = new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews = Collections
.synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;
Handler handler = new Handler();// handler to display images in UI thread
int stub_id;
int widht;
public ImageLoader(Context context, int stub_idx) {
fileCache = new FileCache(context);
executorService = Executors.newFixedThreadPool(5);
stub_id = stub_idx;
}
public void DisplayImage(String url, ImageView imageView, int widht, ProgressBar bar) {
this.widht = widht;
imageViews.put(imageView, url);
Bitmap bitmap = memoryCache.get(url);
if (bitmap != null)
{
bar.setVisibility(View.GONE);
imageView.setImageBitmap(bitmap);
}
else {
queuePhoto(url, imageView, widht, bar);
imageView.setImageResource(stub_id);
}
}
private void queuePhoto(String url, ImageView imageView, int w, ProgressBar bar) {
PhotoToLoad p = new PhotoToLoad(url, imageView, bar);
executorService.submit(new PhotosLoader(p, w));
}
public Bitmap getBitmap(String url, int w) {
File f = fileCache.getFile(url);
// from SD cache
Bitmap b = decodeFile(f, w);
if (b != null)
return b;
// from web
try {
Bitmap bitmap = null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) imageUrl
.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is = conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
conn.disconnect();
bitmap = decodeFile(f, w);
return bitmap;
} catch (Throwable ex) {
ex.printStackTrace();
if (ex instanceof OutOfMemoryError)
memoryCache.clear();
return null;
}
}
// decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f, int w) {
try {
// decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream stream1 = new FileInputStream(f);
BitmapFactory.decodeStream(stream1, null, o);
stream1.close();
// Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE = w;
System.out.println("screen wdth " + widht);
int width_tmp = o.outWidth, height_tmp = o.outHeight;
System.out.println("image with === " + width_tmp);
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
FileInputStream stream2 = new FileInputStream(f);
Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2);
stream2.close();
return bitmap;
}
catch (FileNotFoundException e) {
Log.e(e.getMessage(), "");
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
// Task for the queue
private class PhotoToLoad {
public String url;
public ImageView imageView;
public ProgressBar bar;
public PhotoToLoad(String u, ImageView i, ProgressBar progressBar) {
url = u;
imageView = i;
bar = progressBar;
}
}
class PhotosLoader implements Runnable {
PhotoToLoad photoToLoad;
int w;
PhotosLoader(PhotoToLoad photoToLoad, int w) {
this.photoToLoad = photoToLoad;
this.w = w;
}
#Override
public void run() {
try {
if (imageViewReused(photoToLoad))
return;
Bitmap bmp = getBitmap(photoToLoad.url, w);
memoryCache.put(photoToLoad.url, bmp);
if (imageViewReused(photoToLoad))
return;
BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
handler.post(bd);
} catch (Throwable th) {
th.printStackTrace();
}
}
}
boolean imageViewReused(PhotoToLoad photoToLoad) {
String tag = imageViews.get(photoToLoad.imageView);
return tag == null || !tag.equals(photoToLoad.url);
}
// Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable {
Bitmap bitmap;
PhotoToLoad photoToLoad;
public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
bitmap = b;
photoToLoad = p;
}
public void run() {
if (imageViewReused(photoToLoad))
return;
if (bitmap != null)
photoToLoad.imageView.setImageBitmap(bitmap);
else
photoToLoad.imageView.setImageResource(stub_id);
photoToLoad.bar.setVisibility(View.GONE);
}
}
public void clearCache() {
memoryCache.clear();
fileCache.clear();
}
Then make new class for File cache
public class FileCache {
private File cacheDir;
public FileCache(Context context) {
// Find the dir to save cached images
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED))
cacheDir = new File(
android.os.Environment.getExternalStorageDirectory(),
"LazyList");
else
//cacheDir = url.getCacheDir();
if (!cacheDir.exists())
cacheDir.mkdirs();
}
public File getFile(String url) {
// I identify images by hashcode. Not a perfect solution, good for the
// demo.
String filename = String.valueOf(url.hashCode());
// Another possible solution (thanks to grantland)
// String filename = URLEncoder.encode(url);
File f = new File(cacheDir, filename);
return f;
}
public void clear() {
File[] files = cacheDir.listFiles();
if (files == null)
return;
for (File f : files)
f.delete();
}
}
Then last make Memory cache class , all three seperatly class
public class MemoryCache {
private static final String TAG = "MemoryCache";
private Map<String, Bitmap> cache=Collections.synchronizedMap(
new LinkedHashMap<String, Bitmap>(10,1.5f,true));//Last argument true for LRU ordering
private long size=0;//current allocated size
private long limit=1000000;//max memory in bytes
public MemoryCache(){
//use 25% of available heap size
setLimit(Runtime.getRuntime().maxMemory()/4);
}
public void setLimit(long new_limit){
limit=new_limit;
Log.i(TAG, "MemoryCache will use up to "+limit/1024./1024.+"MB");
}
public Bitmap get(String id){
try{
if(!cache.containsKey(id))
return null;
//NullPointerException sometimes happen here http://code.google.com/p/osmdroid/issues/detail?id=78
return cache.get(id);
}catch(NullPointerException ex){
ex.printStackTrace();
return null;
}
}
public void put(String id, Bitmap bitmap){
try{
if(cache.containsKey(id))
size-=getSizeInBytes(cache.get(id));
cache.put(id, bitmap);
size+=getSizeInBytes(bitmap);
checkSize();
}catch(Throwable th){
th.printStackTrace();
}
}
private void checkSize() {
Log.i(TAG, "cache size="+size+" length="+cache.size());
if(size>limit){
Iterator<Entry<String, Bitmap>> iter=cache.entrySet().iterator();//least recently accessed item will be the first one iterated
while(iter.hasNext()){
Entry<String, Bitmap> entry=iter.next();
size-=getSizeInBytes(entry.getValue());
iter.remove();
if(size<=limit)
break;
}
Log.i(TAG, "Clean cache. New size "+cache.size());
}
}
public void clear() {
try{
//NullPointerException sometimes happen here http://code.google.com/p/osmdroid/issues/detail?id=78
cache.clear();
size=0;
}catch(NullPointerException ex){
ex.printStackTrace();
}
}
long getSizeInBytes(Bitmap bitmap) {
if(bitmap==null)
return 0;
return bitmap.getRowBytes() * bitmap.getHeight();
}
Related
I have used the async task to download the data and then showing those images in the list view I used the cache to store the images as they are repeating but not in an order. But the images gets jumbled up and sometimes they don't download. I tried searching this, but couldn't find that.
This was one of mine dream company question and i didn't clear because of this.
Please help me around.
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private static final String BASE_URL = "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=android&start=";
private static final String IMAGE_JSON_KEY = "unescapedUrl";
private static final String RESULTS_JSON_KEY = "results";
private static final String RESPONSE_DATA_JSON_KEY = "responseData";
private int mCurrentPage;
private ListView mListView;
private Context mContext;
ArrayList<String> mImageUrls;
private LruCache<String, Bitmap> mCache;
private CustomListAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get memory class of this device, exceeding this amount will throw an
// OutOfMemory exception.
final int memClass = ((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE)).getMemoryClass();
// Use 1/8th of the available memory for this memory cache.
final int cacheSize = 1024 * 1024 * memClass / 8;
// Initialize variables
mContext = this;
mCache = new LruCache<String, Bitmap>(cacheSize) {
#Override
protected int sizeOf(String key, Bitmap value) {
// The cache size will be measured in bytes rather than number of items.
return value.getByteCount();
}
};
mListView = (ListView) findViewById(R.id.list_view);
mAdapter = new CustomListAdapter();
mImageUrls = new ArrayList<>();
// If the urls are wrong then
if (mImageUrls.isEmpty() || checkDiff()) {
fetchNewImageUrls();
}
// Set the adapter to the list view
mListView.setAdapter(mAdapter);
}
class BitmapWorkerTask extends AsyncTask<String, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
private String mUrl;
public BitmapWorkerTask(ImageView imageView) {
// Use a WeakReference to ensure the ImageView can be garbage collected
imageViewReference = new WeakReference<ImageView>(imageView);
}
#Override
protected Bitmap doInBackground(String... params) {
String imageUrl = params[0];
mUrl = imageUrl;
Bitmap bitmap = getBitmapFromMemCache(imageUrl);
if (bitmap == null) {
try {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
// Closing the stream after getting the sample size
InputStream inputStream = connection.getInputStream();
byte[] imageByteArray = convertToByteArray(inputStream);
bitmap = decodeSampledBitmap(imageByteArray, 200, 200);
inputStream.close();
if (bitmap != null) {
Log.d(TAG, "Image downloaded: " + imageUrl);
addBitmapToMemoryCache(imageUrl, bitmap);
} else {
Log.d(TAG, "Null Bitmap downloaded for: " + imageUrl);
}
connection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
Log.d(TAG, "Already present in the Cache");
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if (imageViewReference != null && bitmap != null) {
final ImageView imageView = (ImageView) imageViewReference.get();
if (imageView != null && imageView.getTag().equals(mUrl)) {
imageView.setImageBitmap(bitmap);
}
}
}
}
public class CustomListAdapter extends BaseAdapter {
#Override
public int getCount() {
return mImageUrls.size();
}
#Override
public Object getItem(int position) {
return mImageUrls.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Log.d(TAG, "Get View is called for position: " + position);
View view = convertView;
Holder holder = null;
// Holder represents the elements of the view to use
// Here are initialized
if (view == null) {
view = LayoutInflater.from(mContext).inflate(R.layout.row_item, parent, false);
holder = new Holder();
holder.mRowImage = (ImageView) view.findViewById(R.id.image_view);
holder.mRowText = (TextView) view.findViewById(R.id.row_text);
view.setTag(holder);
} else {
holder = (Holder) view.getTag();
}
// Set default image background
holder.mRowImage.setImageResource(R.drawable.ic_launcher);
// here do operations in holder variable example
holder.mRowText.setText("Image Number: " + position);
// Set the tag for the imageview
holder.mRowImage.setTag(mImageUrls.get(position));
new BitmapWorkerTask(holder.mRowImage).execute(mImageUrls.get(position));
return view;
}
}
public static class Holder {
TextView mRowText;
ImageView mRowImage;
}
public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
if (getBitmapFromMemCache(key) == null) {
mCache.put(key, bitmap);
}
}
public Bitmap getBitmapFromMemCache(String key) {
return (Bitmap) mCache.get(key);
}
public Bitmap decodeSampledBitmap(byte[] imageByteArray, int reqWidth, int reqHeight) {
Bitmap bm = null;
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeByteArray(imageByteArray, 0, imageByteArray.length, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
options.inJustDecodeBounds = false;
bm = BitmapFactory.decodeByteArray(imageByteArray, 0, imageByteArray.length, options);
return bm;
}
public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float) height / (float) reqHeight);
} else {
inSampleSize = Math.round((float) width / (float) reqWidth);
}
}
Log.d(TAG, "Sample size is: " + inSampleSize);
return inSampleSize;
}
private void fetchNewImageUrls() {
new AsyncTask<String, Void, Boolean>() {
#Override
protected Boolean doInBackground(String... params) {
try {
StringBuilder response = new StringBuilder();
URL url = new URL(params[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
response.append(inputLine);
in.close();
connection.disconnect();
String resp = response.toString();
Log.d(TAG, "Response is: " + response);
// Parsing the response
JSONObject jsonObject = new JSONObject(resp);
JSONObject jsonObject1 = jsonObject.getJSONObject(RESPONSE_DATA_JSON_KEY);
JSONArray jsonArray = jsonObject1.getJSONArray(RESULTS_JSON_KEY);
for (int i = 0; i < 4; i++) {
JSONObject dataObject = jsonArray.getJSONObject(i);
mImageUrls.add(dataObject.getString(IMAGE_JSON_KEY));
}
mCurrentPage++;
Log.d(TAG, "Number of image urls are: " + mImageUrls.size());
return true;
} catch (JSONException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
#Override
protected void onPostExecute(Boolean value) {
super.onPostExecute(value);
if (checkDiff() && value) {
Log.d(TAG, "Again fetching the Images");
fetchNewImageUrls();
}
if (!value) {
Log.d(TAG, "Error while getting the response");
}
mAdapter.notifyDataSetChanged();
}
}.execute(BASE_URL + mCurrentPage);
}
private boolean checkDiff() {
int diff = mImageUrls.size() - mCurrentPage * 4;
Log.d(TAG, "Diff is: " + diff);
return diff < 8;
}
public static byte[] convertToByteArray(InputStream input) {
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
while ((bytesRead = input.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
return output.toByteArray();
}
}
Since you do not cancel the unfinished "out of view" downloads these may interfere with your gui.
Example
listview line1 shows item#1 with has an async task to download image "a" not completed yet
scroll down, line1 is now invisible;
listview line8 becomes visible recycling item#1 new async task to download image "x"
async task to download image "a" finishes displaying wrong image. Line8 shows image "a" instead of "x"
to solve this you have to cancel the pending unnecessary unfinished async task-s
public static class Holder {
ImageView mRowImage;
String mImageUrl;
// neccessary to cancel unfinished download
BitmapWorkerTask mDownloader;
}
static class BitmapWorkerTask extends AsyncTask<Holder, Void, Bitmap> {
Holder mHolder;
protected Bitmap doInBackground(Holder... holders) {
mHolder = holders[0];
...
}
protected void onPostExecute(...) {
mHolder.mDownloader = null;
if (!isCancelled()) {
this.mHolder.mRowImage.setImageBitmap(image);
}
this.mHolder = null;
}
}
public class CustomListAdapter extends BaseAdapter {
#Override
public View getView(int position, ...) {
...
if (view == null) {
holder = ...
...
} else {
holder = (Holder) view.getTag();
}
...
// cancel unfinished mDownloader
if (holder.mDownloader != null) {
holder.mDownloader.cancel(false);
holder.mDownloader = null;
}
holder.mImageUrl = mImageUrls.get(position);
holder.mDownloader = new BitmapWorkerTask()
holder.mDownloader.execute(holder);
}
}
Here is a working example for this combination of Adapter + Holder + AsyncTask
[Update]
Potential problems with this solution.
Most modern android versions execute only one async task at a time. If you are fetching the images via the web you cannot download multible images at the same time. See running-parallel-asynctask#stackoverflow for details.
There may be promlems with configuration change(like orientation). See #Selvin-s comment below. I have posted this question "what-happens-with-view-references-in-unfinished-asynctask-after-orientation-chan#stackoverflow" to find out more about it.
I am using curlview for curl effect my data contain images for each page in curlview with my code i got blank pages without image which I seted in imageurllist doing json parsing how i got images instead of blank pages.
This is my code.
public class CurlActivity extends Activity {
private CurlView mCurlView;
public String cid;
public ArrayList<String>magazineidlist;
public String middata;
public String url;
public String imgurl;
public Bitmap bitmap;
public ImageLoader imageloder;
public ImageView imageView;
public ArrayList<String>imageurllist;
public GridImageAdapter gadapter;
public CurlActivity c;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_curl);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
getAllMagazineById();
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
if(bundle!=null){
cid = bundle.getString("mid");
Log.d("magazine id", cid);
}
int index = 0;
if (getLastNonConfigurationInstance() != null) {
index = (Integer) getLastNonConfigurationInstance();
}
mCurlView = (CurlView) findViewById(R.id.curl);
}
#Override
public void onPause() {
super.onPause();
mCurlView.onPause();
}
#Override
public void onResume() {
super.onResume();
mCurlView.onResume();
}
#Override
public Object onRetainNonConfigurationInstance() {
return mCurlView.getCurrentIndex();
}
/**
* Bitmap provider.
*/
private class PageProvider implements CurlView.PageProvider {
// Bitmap resources.
private int[] mBitmapIds = { R.layout.sample};
//LinearLayout llout = (LinearLayout) findViewById(R.layout.sample);
#SuppressWarnings("unused")
//ImageView imageView = (ImageView) findViewById(R.id.imageviewsample);
#Override
public int getPageCount() {
return imageurllist.size();
}
private Bitmap loadBitmap(int width, int height, int index) {
LayoutInflater inflater =
(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Log.d("index",String.valueOf(index));
View v = inflater.inflate((mBitmapIds[index]),null);
v.measure(
MeasureSpec.makeMeasureSpec(width,MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight()
,Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.draw(c);
return b;
}
#Override
public void updatePage(CurlPage page, int width, int height, int index) {
switch (index) {
// First case is image on front side, solid colored back.
default:
Bitmap front = loadBitmap(width, height, 0);
page.setTexture(front, CurlPage.SIDE_FRONT);
page.setColor(Color.rgb(180, 180, 180), CurlPage.SIDE_BACK);
break;
/*// Third case is images on both sides.
case 2: {
Bitmap front = loadBitmap(width, height, 1);
Bitmap back = loadBitmap(width, height, 3);
page.setTexture(front, CurlPage.SIDE_FRONT);
page.setTexture(back, CurlPage.SIDE_BACK);
break;
}
// Fourth case is images on both sides - plus they are blend against
// separate colors.
case 3: {
Bitmap front = loadBitmap(width, height, 2);
Bitmap back = loadBitmap(width, height, 1);
page.setTexture(front, CurlPage.SIDE_FRONT);
page.setTexture(back, CurlPage.SIDE_BACK);
page.setColor(Color.argb(127, 170, 130, 255),
CurlPage.SIDE_FRONT);
page.setColor(Color.rgb(255, 190, 150), CurlPage.SIDE_BACK);
break;
}
// Fifth case is same image is assigned to front and back. In this
// scenario only one texture is used and shared for both sides.
case 4:
Bitmap front = loadBitmap(width, height, 0);
page.setTexture(front, CurlPage.SIDE_BOTH);
page.setColor(Color.argb(127, 255, 255, 255),
CurlPage.SIDE_BACK);
break;*/
}
}
}
/**
* CurlView size changed observer.
*/
class SizeChangedObserver implements CurlView.SizeChangedObserver {
#Override
public void onSizeChanged(int w, int h) {
if (w > h) {
mCurlView.setViewMode(CurlView.SHOW_TWO_PAGES);
mCurlView.setMargins(.1f, .05f, .1f, .05f);
} else {
mCurlView.setViewMode(CurlView.SHOW_ONE_PAGE);
//mCurlView.setMargins(.1f, .1f, .1f, .1f);
}
}
}
public Bitmap GetBitmapfromUrl(String scr) {
try {
URL url=new URL(scr);
HttpURLConnection connection=(HttpURLConnection)url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input=connection.getInputStream();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
Bitmap bitmap = BitmapFactory.decodeStream(input, null, options);
// Bitmap bmp = BitmapFactory.decodeStream(input);
return bitmap;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public void getAllMagazineById() {
new AsyncTask<Void, Void, String>() {
ProgressDialog mProgressDialog;
protected void onPostExecute(String result) {
mProgressDialog.dismiss();
magazineidlist = new ArrayList<String>();
imageurllist = new ArrayList<String>();
//imageloder = new ImageLoader(CurlActivity.this);
// LayoutInflater factory = LayoutInflater.from(CurlActivity.this);
// View child = factory.inflate(R.layout.sample, null);
// imageView = (ImageView)child.findViewById(R.id.imageviewsample);
//imageView = (ImageView)findViewById(R.id.imageviewsample);
try {
JSONObject jsob = new JSONObject(result.toString());
if (jsob.getString("msg").equalsIgnoreCase("Success")) {
JSONArray datajson = jsob.getJSONArray("data");
for (int i = 0; i < datajson.length(); i++) {
JSONObject c = datajson.getJSONObject(i);
middata = c.getString("magazine_id");
imgurl = c.getString("image_url");
magazineidlist.add(middata);
imageurllist.add(imgurl);
Log.d("imageurllist value at index" +i, imageurllist.get(i));
//imageloder.DisplayImage(imageurllist.get(i),imageView);
String url = imageurllist.get(i);
Log.d("url val", url);
}
gadapter = new GridImageAdapter(c, imageurllist);
mCurlView.setPageProvider(new PageProvider());
mCurlView.setSizeChangedObserver(new SizeChangedObserver());
mCurlView.setCurrentIndex(0);
mCurlView.setBackgroundColor(0xFF202830);
} else if(jsob.getString("msg").equalsIgnoreCase("Failure")) {
System.out.println("not a valid data");
}
else
{
System.out.println("error");
}
} catch (Exception e) {
Log.e("error", "" + e);
}
}
private void startActivity(Intent i) {
// TODO Auto-generated method stub
}
#Override
protected String doInBackground(Void... arg0) {
// Creating service handler class instance
try {
HttpPost httppost1 = null;
HttpClient httpclient1 = new DefaultHttpClient();
httppost1 = new HttpPost(JsonKey.MAIN_URL);
// Add your data
List<NameValuePair> nameValuePairs1 = new ArrayList<NameValuePair>(
2);
nameValuePairs1.add(new BasicNameValuePair("action",
"GetMagazinePageImagesbyid"));
nameValuePairs1.add(new BasicNameValuePair("iMagezineId",
cid));
httppost1.setEntity(new UrlEncodedFormEntity(
nameValuePairs1));
// Execute HTTP Post Request
HttpResponse response1 = httpclient1.execute(httppost1);
BufferedReader in1 = new BufferedReader(
new InputStreamReader(response1.getEntity()
.getContent()));
StringBuffer sb1 = new StringBuffer("");
String line1 = "";
while ((line1 = in1.readLine()) != null) {
sb1.append(line1);
}
in1.close();
Log.e(" Get All magazine original data", sb1.toString());
return sb1.toString();
} catch (Exception e) {
Log.e("Get All magazine response problem", "" + e);
return " ";
}
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
mProgressDialog = new ProgressDialog(CurlActivity.this);
mProgressDialog.setTitle("");
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.setMessage("Please Wait...");
mProgressDialog.show();
}
}.execute();
}
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
// Log exception
return null;
}
}
Bitmap drawable_from_url(String url) throws java.net.MalformedURLException, java.io.IOException {
Bitmap x;
HttpURLConnection connection = (HttpURLConnection)new URL(url) .openConnection();
connection.setRequestProperty("User-agent","Mozilla/4.0");
connection.connect();
InputStream input = connection.getInputStream();
x = BitmapFactory.decodeStream(input);
return x;
}
public class GridImageAdapter extends BaseAdapter {
public Context mContext;
// public final String[] web;
// final int ImageId[];
public CurlActivity activity;
public ImageLoader imageloader;
// Constructor
public GridImageAdapter(CurlActivity c, ArrayList<String> imageUrl) {
// TODO Auto-generated constructor stub
mContext = c;
imageurllist = imageUrl;
imageloader = new ImageLoader(CurlActivity.this);
}
public int getCount() {
return imageurllist.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
View grid;
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
grid = new View(mContext);
grid = inflater.inflate(R.layout.sample, null);
ImageView img = (ImageView) grid.findViewById(R.id.imageviewsample);
imageloader.DisplayImage(imageurllist.get(position), img);
}
/*
* ImageView imageView; if (convertView == null) { imageView = new
* ImageView(mContext); imageView.setLayoutParams(new
* GridView.LayoutParams(85, 85));
* imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
* imageView.setPadding(8, 8, 8, 8); }
*/else {
grid = (View) convertView;
}
/*
* imageView.setImageResource(mThumbIds[position]); return
* imageView;
*/
return grid;
}
// Keep all Images in array
/*
* public Integer[] mThumbIds = { R.drawable.nightlife,
* R.drawable.coffee, R.drawable.shopping, R.drawable.seeanddo,
*
* };
*/
public Bitmap StringToBitMap(String encodedString) {
try {
byte[] encodeByte = Base64
.decode(encodedString, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0,
encodeByte.length);
return bitmap;
} catch (Exception e) {
e.getMessage();
return null;
}
}
}
}
I want to crate curlview with dynemic data. I used imageview to display image into curlview because my api contain image in data. but image is not displayed into imageview how i do this?
Below is my code.
public class CurlActivity extends Activity {
private CurlView mCurlView;
public String cid;
public ArrayList<String>magazineidlist;
public String middata;
public String url;
public String imgurl;
public Bitmap bitmap;
public ImageLoader imageloder;
public ImageView imageView;
public ArrayList<String>imageurllist;
public GridImageAdapter gadapter;
public CurlActivity c;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_curl);
gadapter = new GridImageAdapter(c, imageurllist);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
getAllMagazineById();
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
if(bundle!=null){
cid = bundle.getString("mid");
Log.d("magazine id", cid);
}
int index = 0;
if (getLastNonConfigurationInstance() != null) {
index = (Integer) getLastNonConfigurationInstance();
}
mCurlView = (CurlView) findViewById(R.id.curl);
}
#Override
public void onPause() {
super.onPause();
mCurlView.onPause();
}
#Override
public void onResume() {
super.onResume();
mCurlView.onResume();
}
#Override
public Object onRetainNonConfigurationInstance() {
return mCurlView.getCurrentIndex();
}
/**
* Bitmap provider.
*/
private class PageProvider implements CurlView.PageProvider {
// Bitmap resources.
private int[] mBitmapIds = { R.layout.sample};
//LinearLayout llout = (LinearLayout) findViewById(R.layout.sample);
#SuppressWarnings("unused")
//ImageView imageView = (ImageView) findViewById(R.id.imageviewsample);
#Override
public int getPageCount() {
return imageurllist.size();
}
private Bitmap loadBitmap(int width, int height, int index) {
LayoutInflater inflater =
(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Log.d("index",String.valueOf(index));
View v = inflater.inflate(mBitmapIds[index],null);
v.measure(
MeasureSpec.makeMeasureSpec(width,MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight()
,Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.draw(c);
return b;
}
#Override
public void updatePage(CurlPage page, int width, int height, int index) {
switch (index) {
// First case is image on front side, solid colored back.
default:
Bitmap front = loadBitmap(width, height, 0);
page.setTexture(front, CurlPage.SIDE_FRONT);
page.setColor(Color.rgb(180, 180, 180), CurlPage.SIDE_BACK);
break;
/*// Third case is images on both sides.
case 2: {
Bitmap front = loadBitmap(width, height, 1);
Bitmap back = loadBitmap(width, height, 3);
page.setTexture(front, CurlPage.SIDE_FRONT);
page.setTexture(back, CurlPage.SIDE_BACK);
break;
}
// Fourth case is images on both sides - plus they are blend against
// separate colors.
case 3: {
Bitmap front = loadBitmap(width, height, 2);
Bitmap back = loadBitmap(width, height, 1);
page.setTexture(front, CurlPage.SIDE_FRONT);
page.setTexture(back, CurlPage.SIDE_BACK);
page.setColor(Color.argb(127, 170, 130, 255),
CurlPage.SIDE_FRONT);
page.setColor(Color.rgb(255, 190, 150), CurlPage.SIDE_BACK);
break;
}
// Fifth case is same image is assigned to front and back. In this
// scenario only one texture is used and shared for both sides.
case 4:
Bitmap front = loadBitmap(width, height, 0);
page.setTexture(front, CurlPage.SIDE_BOTH);
page.setColor(Color.argb(127, 255, 255, 255),
CurlPage.SIDE_BACK);
break;*/
}
}
}
/**
* CurlView size changed observer.
*/
class SizeChangedObserver implements CurlView.SizeChangedObserver {
#Override
public void onSizeChanged(int w, int h) {
if (w > h) {
mCurlView.setViewMode(CurlView.SHOW_TWO_PAGES);
mCurlView.setMargins(.1f, .05f, .1f, .05f);
} else {
mCurlView.setViewMode(CurlView.SHOW_ONE_PAGE);
//mCurlView.setMargins(.1f, .1f, .1f, .1f);
}
}
}
public Bitmap GetBitmapfromUrl(String scr) {
try {
URL url=new URL(scr);
HttpURLConnection connection=(HttpURLConnection)url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input=connection.getInputStream();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
Bitmap bitmap = BitmapFactory.decodeStream(input, null, options);
// Bitmap bmp = BitmapFactory.decodeStream(input);
return bitmap;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public void getAllMagazineById() {
new AsyncTask<Void, Void, String>() {
ProgressDialog mProgressDialog;
protected void onPostExecute(String result) {
mProgressDialog.dismiss();
magazineidlist = new ArrayList<String>();
imageurllist = new ArrayList<String>();
//imageloder = new ImageLoader(CurlActivity.this);
// LayoutInflater factory = LayoutInflater.from(CurlActivity.this);
// View child = factory.inflate(R.layout.sample, null);
// imageView = (ImageView)child.findViewById(R.id.imageviewsample);
//imageView = (ImageView)findViewById(R.id.imageviewsample);
try {
JSONObject jsob = new JSONObject(result.toString());
if (jsob.getString("msg").equalsIgnoreCase("Success")) {
JSONArray datajson = jsob.getJSONArray("data");
for (int i = 0; i < datajson.length(); i++) {
JSONObject c = datajson.getJSONObject(i);
middata = c.getString("magazine_id");
imgurl = c.getString("image_url");
magazineidlist.add(middata);
imageurllist.add(imgurl);
Log.d("imageurllist value at index" +i, imageurllist.get(i));
//imageloder.DisplayImage(imageurllist.get(i),imageView);
String url = imageurllist.get(i);
Log.d("url val", url);
}
mCurlView.setPageProvider(new PageProvider());
mCurlView.setSizeChangedObserver(new SizeChangedObserver());
//mCurlView.setCurrentIndex(0);
mCurlView.setBackgroundColor(0xFF202830);
} else if(jsob.getString("msg").equalsIgnoreCase("Failure")) {
System.out.println("not a valid data");
}
else
{
System.out.println("error");
}
} catch (Exception e) {
Log.e("error", "" + e);
}
}
private void startActivity(Intent i) {
// TODO Auto-generated method stub
}
#Override
protected String doInBackground(Void... arg0) {
// Creating service handler class instance
try {
HttpPost httppost1 = null;
HttpClient httpclient1 = new DefaultHttpClient();
httppost1 = new HttpPost(JsonKey.MAIN_URL);
// Add your data
List<NameValuePair> nameValuePairs1 = new ArrayList<NameValuePair>(
2);
nameValuePairs1.add(new BasicNameValuePair("action",
"GetMagazinePageImagesbyid"));
nameValuePairs1.add(new BasicNameValuePair("iMagezineId",
cid));
httppost1.setEntity(new UrlEncodedFormEntity(
nameValuePairs1));
// Execute HTTP Post Request
HttpResponse response1 = httpclient1.execute(httppost1);
BufferedReader in1 = new BufferedReader(
new InputStreamReader(response1.getEntity()
.getContent()));
StringBuffer sb1 = new StringBuffer("");
String line1 = "";
while ((line1 = in1.readLine()) != null) {
sb1.append(line1);
}
in1.close();
Log.e(" Get All magazine original data", sb1.toString());
return sb1.toString();
} catch (Exception e) {
Log.e("Get All magazine response problem", "" + e);
return " ";
}
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
mProgressDialog = new ProgressDialog(CurlActivity.this);
mProgressDialog.setTitle("");
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.setMessage("Please Wait...");
mProgressDialog.show();
}
}.execute();
}
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
// Log exception
return null;
}
}
Bitmap drawable_from_url(String url) throws java.net.MalformedURLException, java.io.IOException {
Bitmap x;
HttpURLConnection connection = (HttpURLConnection)new URL(url) .openConnection();
connection.setRequestProperty("User-agent","Mozilla/4.0");
connection.connect();
InputStream input = connection.getInputStream();
x = BitmapFactory.decodeStream(input);
return x;
}
public class GridImageAdapter extends BaseAdapter {
public Context mContext;
// public final String[] web;
// final int ImageId[];
public CurlActivity activity;
public ImageLoader imageloader;
// Constructor
public GridImageAdapter(CurlActivity c, ArrayList<String> imageUrl) {
// TODO Auto-generated constructor stub
mContext = c;
imageurllist = imageUrl;
imageloader = new ImageLoader(CurlActivity.this);
}
public int getCount() {
return imageurllist.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
View grid;
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
grid = new View(mContext);
grid = inflater.inflate(R.layout.sample, null);
ImageView img = (ImageView) grid.findViewById(R.id.imageviewsample);
imageloader.DisplayImage(imageurllist.get(position), img);
}
/*
* ImageView imageView; if (convertView == null) { imageView = new
* ImageView(mContext); imageView.setLayoutParams(new
* GridView.LayoutParams(85, 85));
* imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
* imageView.setPadding(8, 8, 8, 8); }
*/else {
grid = (View) convertView;
}
/*
* imageView.setImageResource(mThumbIds[position]); return
* imageView;
*/
return grid;
}
// Keep all Images in array
/*
* public Integer[] mThumbIds = { R.drawable.nightlife,
* R.drawable.coffee, R.drawable.shopping, R.drawable.seeanddo,
*
* };
*/
public Bitmap StringToBitMap(String encodedString) {
try {
byte[] encodeByte = Base64
.decode(encodedString, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0,
encodeByte.length);
return bitmap;
} catch (Exception e) {
e.getMessage();
return null;
}
}
}
}
I need to add a progress listener to each element of the horizontal list view, how can I do that?
For each item I upload a file.
I wanna to do something like that but holder is not final, so I have an error.
public class UploadsViewAdapter extends BaseAdapter {
private Context mContext;
private int mLayoutResourceId;
List<Upload> listFileToUpload;
public UploadsViewAdapter(Context context, int layoutResourceId, List<Upload> data) {
this.mLayoutResourceId = layoutResourceId;
this.mContext = context;
this.listFileToUpload = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
row = inflater.inflate(mLayoutResourceId, parent, false);
holder = new ViewHolder();
holder.image = (ImageView) row.findViewById(R.id.upload_item_image);
holder.progressUpdate = (ProgressBar) row.findViewById(R.id.progressUpdate);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
final Upload item = getItem(position);
holder.image.setImageBitmap(item.getThumbnail(160, 160));
item.setProgressListener(new ProgressListener() {
#Override
public void onProgress(int progress) {
holder.progressUpdate.setProgress(item.getProgress());
}
});
holder.progressUpdate.setProgress(item.getProgress());
return row;
}
static class ViewHolder {
ImageView image;
ProgressBar progressUpdate;
}
public void updateListFileToUpdate(List<Upload> listFileToUpload) {
this.listFileToUpload = listFileToUpload;
}
#Override
public int getCount() {
return listFileToUpload.size();
}
#Override
public Upload getItem(int location) {
return listFileToUpload.get(location);
}
#Override
public long getItemId(int position) {
return 0;
}
}
Class Update.java
public class Upload {
public String path;
public String type;
private int mProgress = 0;
private ProgressListener mListener;
public Upload(String path, String type) {
this.path = path;
this.type = type;
}
public void setProgressListener(ProgressListener listener) {
mListener = listener;
}
public void setProgress(int progress) {
mProgress = progress;
if (mListener != null) {
mListener.onProgress(progress);
}
}
public int getProgress() {
return mProgress;
}
public Bitmap getThumbnail(int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while (
(halfHeight / inSampleSize) > reqHeight &&
(halfWidth / inSampleSize) > reqWidth
) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
public interface ProgressListener {
public void onProgress(int progress);
}
}
Class which updates the file:
public class TheFormFragment extends Fragment {
private AmazonS3Client mS3Client = new AmazonS3Client(
new BasicAWSCredentials(Config.AWS_ACCESS_KEY, Config.AWS_SECRET_KEY));
public static final int RESULT_PHOTO_DISK = 10;
public static final int RESULT_PHOTO_APN = 100;
public static final int RESULT_VIDEO_APN = 1000;
public static final String INTENT_PHOTO_APN_PATH = "INTENT_PHOTO_APN_PATH";
public static final String INTENT_VIDEO_APN_PATH = "INTENT_VIDEO_APN_PATH";
private List<Medias> mTheFormPictures;
private static Activity mActivity;
private static ArrayList<Upload> mQueue;
private KeyboardEventLinearLayout mLinearLayoutBackground;
private LinearLayout mLinearLayoutPublish;
private TextView mTextViewPublish;
private ImageView mImageViewPublish; // todo image du bouton
private EditText mEditTextText;
private TextView mTextViewTitle;
private CircularImageView mCircularImageViewAvatar;
private ImageButton mImageButtonClose;
private ImageButton mImageButtonCamera;
private ImageButton mImageButtonLibrary;
private Tag[] mTags = null;
private Range mAutocompleting;
private LinearLayout mAutocompleteContainer;
private HorizontalListView mUploadsList;
private UploadsViewAdapter mUploading;
/**Contains list of images, vidoe to update*/
private List<Upload> listFileToUpload;
private KeyboardEventLinearLayout.KeyboardListener mKeyboardListener = new KeyboardEventLinearLayout.KeyboardListener() {
#Override
public void onShow() {
if (mUploadsList != null) {
mUploadsList.setVisibility(View.GONE);
}
}
#Override
public void onHide() {
if (mUploadsList != null) {
mUploadsList.setVisibility(View.VISIBLE);
}
}
};
private class Range {
public int start;
public int end;
public String value;
public Range(int start, int end, String value) {
this.start = start;
this.end = end;
this.value = value;
}
}
private TextWatcher textWatcher = new TextWatcher() {
#Override
public void onTextChanged(CharSequence text, int start, int oldCount, int newCount) {
String before = text.subSequence(0, start + newCount).toString();
Range range = findEditingTag(before);
autocompete(range);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void afterTextChanged(Editable s) {}
};
private OnClickListener mAutocompleteItemClickListener = new OnClickListener() {
#Override
public void onClick(View view) {
Editable text = mEditTextText.getText();
CharSequence tag = ((TextView) view).getText();
text.replace(mAutocompleting.start, mAutocompleting.end, tag);
}
};
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mActivity = activity;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_the_form, container, false);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
mTheFormPictures = new ArrayList<Medias>();
mQueue = new ArrayList<Upload>();
mS3Client.setRegion(Region.getRegion(Config.AWS_REGION));
mLinearLayoutBackground = (KeyboardEventLinearLayout) mActivity.findViewById(R.id.linearLayoutBackground);
mLinearLayoutPublish = (LinearLayout) mActivity.findViewById(R.id.linearLayoutPublish);
mTextViewPublish = (TextView) mActivity.findViewById(R.id.textViewPublish);
mTextViewTitle = (TextView) mActivity.findViewById(R.id.textViewTitle);
mImageViewPublish = (ImageView) mActivity.findViewById(R.id.imageViewPublish);
mCircularImageViewAvatar = (CircularImageView) mActivity.findViewById(R.id.circularImageViewAvatar);
mEditTextText = (EditText) mActivity.findViewById(R.id.editTextText);
mImageButtonClose = (ImageButton) mActivity.findViewById(R.id.imageButtonClose);
mImageButtonCamera = (ImageButton) mActivity.findViewById(R.id.imageButtonCamera);
mImageButtonLibrary = (ImageButton) mActivity.findViewById(R.id.imageButtonLibrary);
mAutocompleteContainer = (LinearLayout) mActivity.findViewById(R.id.autocompleteLayout);
mUploadsList = (HorizontalListView) mActivity.findViewById(R.id.uploadsList);
listFileToUpload =new ArrayList<Upload>();
mUploading = new UploadsViewAdapter(mActivity, R.layout.upload_item, listFileToUpload);
mUploadsList.setAdapter(mUploading);
mLinearLayoutBackground.setKeyboardListener(mKeyboardListener);
configure();
super.onActivityCreated(savedInstanceState);
}
#SuppressLint("NewApi")
#SuppressWarnings("deprecation")
private void configure() {
AQuery aq = new AQuery(mActivity);
ImageOptions options = new ImageOptions();
//options.round = 180;
options.fileCache = false;
options.memCache = true;
//options.animation = AQuery.FADE_IN;
User user = Preferences.getUser(mActivity);
if (user != null) {
mTextViewTitle.setText(user.getFirst_name() + " " + user.getLast_name());
if (user.getAvatar() != null && user.getAvatar().length() > 0) {
aq.id(mCircularImageViewAvatar).image(user.getAvatar(), options);
}
}
StatusConfigTheForm configTheForm = Preferences.getConfigTheForm(mActivity);
if (configTheForm != null) {
Log.i("theform config success");
Log.d("avatar: " + user.getAvatar() + " " + configTheForm.getBorderWidth());
if (configTheForm.getColors().getBackground().length == 3) {
mLinearLayoutBackground.setBackgroundColor(Color.parseColor(Utils.getHexaColor(configTheForm.getColors().getBackground())));
}
if (configTheForm.getColors().getBackgrounPublishButton().length == 3) {
// mButtonPublish.setBackgroundColor(Color.parseColor(Utils.getHexaColor(configTheForm.getColors().getBackgrounPublishButton())));
// prepare
int roundRadius = 6;
// normal state
GradientDrawable background_normal = new GradientDrawable();
background_normal.setColor(Color.parseColor(Utils.getHexaColor(configTheForm.getColors().getBackgrounPublishButton())));
background_normal.setCornerRadius(roundRadius);
// pressed state
GradientDrawable bacground_pressed = new GradientDrawable();
bacground_pressed.setColor(Color.parseColor(Utils.getHexaColor(configTheForm.getColors().getBackgrounPublishButton()).replace("#", "#CC"))); // opacity
bacground_pressed.setCornerRadius(roundRadius);
// states (normal and pressed)
StateListDrawable states = new StateListDrawable();
states.addState(new int[] {android.R.attr.state_pressed}, bacground_pressed);
states.addState(new int[] {-android.R.attr.state_pressed}, background_normal);
if (Build.VERSION.SDK_INT >= 16) {
mLinearLayoutPublish.setBackground(states);
} else {
mLinearLayoutPublish.setBackgroundDrawable(states);
}
}
if (configTheForm.getColors().getBackgroundTextView().length == 3) {
mEditTextText.setBackgroundColor(Color.parseColor(Utils.getHexaColor(configTheForm.getColors().getBackgroundTextView())));
}
if (configTheForm.getColors().getBorderColorPicture().length == 3) {
mCircularImageViewAvatar.setBorderColor(Utils.getHexaColor(configTheForm.getColors().getBorderColorPicture()));
}
// add color tag here
if (configTheForm.getColors().getColorTextPublish().length == 3) {
mTextViewPublish.setTextColor(Color.parseColor(Utils.getHexaColor(configTheForm.getColors().getColorTextPublish())));
}
if (configTheForm.getColors().getColorTextAttachment().length == 3) {
mCircularImageViewAvatar.setBorderColor(Utils.getHexaColor(configTheForm.getColors().getColorTextAttachment()));
}
if (configTheForm.getColors().getColorTextUser().length == 3) {
mTextViewTitle.setTextColor(Color.parseColor(Utils.getHexaColor(configTheForm.getColors().getColorTextUser())));
}
if (configTheForm.getBorderWidth() > 0) {
mCircularImageViewAvatar.setBorderWidth(configTheForm.getBorderWidth() * Integer.valueOf(Float.valueOf(getResources().getDisplayMetrics().density).intValue()));
}
// pictures
if (configTheForm.getPictures() != null) {
String baseUrl = configTheForm.getUrlPicto() + configTheForm.getFolder() + File.separator;
String ext = Utils.setExtension(mActivity, Config.PICTURE_EXTENSION);
Pictures pics = configTheForm.getPictures();
if (configTheForm.getPictures().getPictureBack() != null) {
aq.id(mImageButtonClose).image(baseUrl + pics.getPictureBack() + ext, options);
}
if (configTheForm.getPictures().getPictureCamera() != null) {
aq.id(mImageButtonCamera).image(baseUrl + pics.getPictureCamera() + ext, options);
}
if (configTheForm.getPictures().getPictureLibrary() != null) {
aq.id(mImageButtonLibrary).image(baseUrl + pics.getPictureLibrary() + ext, options);
}
if (configTheForm.getPictures().getPicturePublish() != null) {
mImageViewPublish.setVisibility(View.VISIBLE);
aq.id(mImageViewPublish).image(baseUrl + pics.getPicturePublish() + ext, options);
} else {
mImageViewPublish.setVisibility(View.GONE);
}
}
}
mEditTextText.addTextChangedListener(textWatcher);
}
private Range findEditingTag(String text) {
Pattern pattern = Pattern.compile("#[A-z0-9_]+$");
Matcher match = pattern.matcher(text);
if (match.find()) {
String value = text.substring(match.start());
return new Range(match.start(), match.end(), value);
}
return null;
}
private void autocompete(Range range) {
mAutocompleting = range;
mAutocompleteContainer.removeAllViews();
if (range != null && mTags != null) {
String tag;
for (int i = 0; i < mTags.length; i++) {
tag = "#" + mTags[i].getName();
if (tag.startsWith(range.value) && tag.equals(range.value) == false) {
addAutocompleteItem(tag);
}
}
}
}
#SuppressWarnings("deprecation")
#SuppressLint("NewApi")
private void addAutocompleteItem(String text) {
Drawable background = mActivity.getResources().getDrawable(R.drawable.autocomplete_item);
int textColor = mActivity.getResources().getColor(R.color.autocomplete_item_text);
TextView view = new TextView(mActivity);
view.setText(text);
view.setTextColor(textColor);
view.setPadding(20, 10, 20, 10);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
params.setMargins(10, 0, 10, 0);
view.setLayoutParams(params);
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
view.setBackgroundDrawable(background);
} else {
view.setBackground(background);
}
view.setClickable(true);
view.setOnClickListener(mAutocompleteItemClickListener);
mAutocompleteContainer.addView(view);
}
private void updateProgress() {
//int progress = 0;
//for (Upload file: mUploading) {
// progress += file.getProgress();
//}
//progress /= mUploading.size();
//mProgressBarFile.setProgress(progress);
//mTextViewFileProgress.setText(String.format(getString(R.string.theform_text_file_progress), Integer.valueOf(progress).toString()));
}
private class S3PutObjectTask extends AsyncTask<Upload, Integer, S3TaskResult> {
//private Dialog progressDialog;
ObjectMetadata mMetadata = new ObjectMetadata();
private String mS3Filename;
private Upload mFile;
#Override
protected void onPreExecute() {
updateProgress();
}
#Override
protected void onProgressUpdate(Integer... values) {
int progress = Integer.valueOf( (int) ((values[0] * 100) / mMetadata.getContentLength()) );
mFile.setProgress(progress);
updateProgress();
super.onProgressUpdate(values);
}
protected S3TaskResult doInBackground(Upload... files) {
if (files == null || files.length != 1 || files[0] == null) {
return null;
} else {
mFile = files[0];
}
ContentResolver resolver = mActivity.getContentResolver();
// The file location of the image selected.
Uri selectedSource = Uri.parse(mFile.path);
if (mFile.type.equals("image")) {
String size = null;
String fileSizeColumn[] = { OpenableColumns.SIZE };
Cursor cursor = resolver.query(selectedSource, fileSizeColumn, null, null, null);
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
int sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE);
// If the size is unknown, the value stored is null. But since an int can't be
// null in java, the behavior is implementation-specific, which is just a fancy
// term for "unpredictable". So as a rule, check if it's null before assigning
// to an int. This will happen often: The storage API allows for remote
// files, whose size might not be locally known.
if (!cursor.isNull(sizeIndex)) {
// Technically the column stores an int, but cursor.getString will do the
// conversion automatically.
size = cursor.getString(sizeIndex);
}
cursor.close();
}
mMetadata.setContentType(resolver.getType(selectedSource));
if (size != null) {
mMetadata.setContentLength(Long.parseLong(size));
}
}
if (mMetadata.getContentType() == null) {
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inJustDecodeBounds = true;
BitmapFactory.decodeFile(selectedSource.toString(), opt);
mMetadata.setContentType(opt.outMimeType);
}
if (mMetadata.getContentLength() <= 0) {
mMetadata.setContentLength(new File(selectedSource.toString()).length());
}
selectedSource = Uri.parse("file://" + selectedSource.toString().replace("content://", ""));
S3TaskResult result = new S3TaskResult();
// Put the image data into S3.
try {
Calendar cal = Calendar.getInstance();
if (mFile.type.equals("image")) {
mS3Filename = Long.valueOf(cal.getTime().getTime()).toString() + ".jpg";
} else {
mS3Filename = Long.valueOf(cal.getTime().getTime()).toString() + ".mp4";
}
PutObjectRequest por = new PutObjectRequest(
Config.getPictureBucket(cal.getTime().getTime()), mS3Filename,
resolver.openInputStream(selectedSource), mMetadata
).withGeneralProgressListener(new ProgressListener() {
int total = 0;
#Override
public void progressChanged(ProgressEvent pv) {
total += (int) pv.getBytesTransferred();
publishProgress(total);
}
});
mS3Client.putObject(por);
result.setName(mS3Filename);
} catch (Exception exception) {
exception.printStackTrace();
result.setName(null);
result.setErrorMessage(exception.getMessage());
}
return result;
}
protected void onPostExecute(S3TaskResult result) {
//mProgressBarFile.setProgress(0);
//mTextViewFileProgress.setText("");
// AWS Error
if (result != null && result.getErrorMessage() != null && result.getName() == null) {
FastDialog.showDialog(mActivity, FastDialog.SIMPLE_DIALOG, result.getErrorMessage());
} else {
// add picture name
mTheFormPictures.add(new Medias(result.getName()));
}
}
}
public static String getRealPathFromUri(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
/** close activity **/
public void close(View v) {
mActivity.finish();
}
/** select picture **/
public void selectPicture(View v) {
//Intent intent;
Intent intent = new Intent(
Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
/*if (Build.VERSION.SDK_INT < 19) {
intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
} else {
intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
}
if (Build.VERSION.SDK_INT >= 18) {
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
}*/
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setType("image/* video/*");
startActivityForResult(intent, RESULT_PHOTO_DISK);
}
/** take picture **/
public void tackePicture(View v) {
ApnActivity.show(mActivity, RESULT_PHOTO_APN);
}
/** record video **/
public void recordVideo(View v) {
RecordVideoActivity.show(mActivity, RESULT_VIDEO_APN);
}
/** publish button **/
public void publish(View v) {
// object
WebViewTheFormResult theFormResult = new WebViewTheFormResult(mEditTextText.getText().toString(), mTheFormPictures);
if (theFormResult.isEmpty()) {
FastDialog.showDialog(mActivity, FastDialog.SIMPLE_DIALOG, getString(R.string.theform_publish_error));
} else {
// intent
Intent dataIntent = new Intent();
Bundle bundle = new Bundle();
bundle.putSerializable(WebViewActivity.INTENT_OBJECT, (Serializable) theFormResult);
dataIntent.putExtras(bundle);
mActivity.setResult(Activity.RESULT_OK, dataIntent);
mActivity.finish();
}
}
#SuppressLint("NewApi")
public static void actionOnActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_CANCELED) {
return;
}
if (requestCode != RESULT_PHOTO_APN && requestCode != RESULT_VIDEO_APN) {
requestCode = RESULT_PHOTO_DISK;
}
switch (requestCode) {
case RESULT_PHOTO_DISK:
if (Build.VERSION.SDK_INT >= 18 && data.getData() == null) {
ClipData clipdata = data.getClipData();
for (int i = 0, l = clipdata.getItemCount(); i < l; i++) {
onDiskResult(clipdata.getItemAt(i).getUri());
}
} else {
onDiskResult(data.getData());
}
break;
case RESULT_PHOTO_APN:
onApnPhotoResult(data);
break;
case RESULT_VIDEO_APN:
onApnVideoResult(data);
break;
}
}
private static void onDiskResult(Uri selectedImage) {
InputStream imageStream;
try {
File file = new File(
Environment.getExternalStorageDirectory() + File.separator +
"Android" + File.separator +
"data" + File.separator +
mActivity.getPackageName()
);
if (new File(file.getAbsolutePath()).exists() == false) {
file.mkdirs();
}
imageStream = mActivity.getContentResolver().openInputStream(selectedImage);
Bitmap goodPicture = BitmapFactory.decodeStream(imageStream);
String filePath = file.getAbsoluteFile().toString() + "/" + String.valueOf(Utils.uid()) + Config.PHOTO_TMP_NAME;
try {
//goodPicture = ThumbnailUtils.createVideoThumbnail(filePath, MediaStore.Images.Thumbnails.MINI_KIND);
FileOutputStream out = new FileOutputStream(filePath);
goodPicture = Bitmap.createScaledBitmap(goodPicture, 800, 600, false);
goodPicture.compress(Bitmap.CompressFormat.JPEG, 80, out);
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
}
queueFile(filePath, "image");
} catch (FileNotFoundException e1) {
e1.printStackTrace();
return;
}
}
private static void onApnPhotoResult(Intent data) {
String filePath = data.getExtras().getString(TheFormFragment.INTENT_PHOTO_APN_PATH);
if (filePath.equals(Integer.valueOf(RESULT_VIDEO_APN).toString())) {
RecordVideoActivity.show(mActivity, RESULT_VIDEO_APN);
} else {
queueFile(filePath, "image");
}
}
private static void onApnVideoResult(Intent data) {
String filePath = data.getExtras().getString(TheFormFragment.INTENT_VIDEO_APN_PATH);
if (filePath.equals(Integer.valueOf(RESULT_PHOTO_APN).toString())) {
ApnActivity.show(mActivity, RESULT_PHOTO_APN);
} else {
queueFile(filePath, "video");
}
}
private static void queueFile(String filePath, String fileType) {
mQueue.add(new Upload(filePath, fileType));
}
#Override
public void onResume() {
fetchTags();
while (mQueue.size() > 0) {
uploadFile(mQueue.remove(mQueue.size() - 1));
}
super.onResume();
}
private void uploadFile(Upload file) {
new S3PutObjectTask().execute(file);
listFileToUpload.add(file);
mUploading.updateListFileToUpdate(listFileToUpload);
mUploading.notifyDataSetChanged();
}
private void fetchTags() {
Api.getTags(mActivity, new Api.Callback() {
#Override
public void onSuccess(String json) {
Gson gson = new Gson();
mTags = gson.fromJson(json, Tag[].class);
}
});
}
}
How can I resolve the problem?
Something like this should be enough:
...
holder.image.setImageBitmap(item.getThumbnail(160, 160));
final ViewHolder finalHolder = holder;
item.setProgressListener(new ProgressListener() {
#Override
public void onProgress(int progress) {
finalHolder.progressUpdate.setProgress(item.getProgress());
}
});
finalHolder.progressUpdate.setProgress(item.getProgress());
Think that you can remove setProgressListener() from Upload class.
Instead add a ProgressBar variable and a method setProgressBar() to Upload.
In getView():
Upload upload = getItem(position )
upload.setProgressBar(holder.progressUpdate);
In Upload: in setProgress() you can now directly address the ProgressBar variable
this is the setProgress() that in your AsyncTask is called with mFile.setProgress(progress);
Instead of removing better out comment the function and the call.
Untested. Please test. This will not be much work.
Don't make holder final. It will not help you. You also made item final in order to use it in onProgress. But that will not do either. You have to determine the right holder with getTag() and if you put position in the holder (as int variable) then you can use holder.position to get the right item again with a getItem(holder.position)
Thanks for your responses all.
I resolved the problem like this:
public class UploadsViewAdapter extends BaseAdapter {
private Context mContext;
List<Upload> listFileToUpload;
UploadsViewAdapter instanceUploadsViewAdapter;
public UploadsViewAdapter(Context context,
List<Upload> data) {
this.mContext = context;
this.listFileToUpload = data;
this.instanceUploadsViewAdapter = this;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
row = inflater.inflate(R.layout.upload_item, parent, false);
holder = new ViewHolder();
holder.image = (ImageView) row.findViewById(R.id.upload_item_image);
holder.play = (ImageView) row.findViewById(R.id.play);
holder.progressUpdate = (ProgressBar) row
.findViewById(R.id.progressUpdate);
holder.deleteFileUploaded = (ImageView) row.findViewById(R.id.delete_file_uploaded);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
final Upload item = getItem(position);
holder.image.setImageBitmap(item.getThumbnail(160, 160));
final ViewHolder finalHolder = holder;
item.setProgressListener(new ProgressListener() {
#Override
public void onProgress(int progress) {
//item.setProgress(progress);
finalHolder.progressUpdate.setProgress(progress);
if(progress==100){
finalHolder.image.setAlpha(1.0f);
finalHolder.progressUpdate.setVisibility(View.GONE);
}
else{
finalHolder.image.setAlpha(0.5f);
finalHolder.progressUpdate.setVisibility(View.VISIBLE);
}
}
});
if(item.getProgress()==100){
finalHolder.image.setAlpha(1.0f);
finalHolder.progressUpdate.setVisibility(View.GONE);
}
else{
finalHolder.image.setAlpha(0.5f);
finalHolder.progressUpdate.setVisibility(View.VISIBLE);
}
holder.deleteFileUploaded.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
listFileToUpload.remove(position);
instanceUploadsViewAdapter.notifyDataSetChanged();
}
});
if(item.getType().equals(EnumTypeFile.IMAGE.getTypeFile())){
holder.play.setVisibility(View.GONE);
}
else{
holder.play.setVisibility(View.VISIBLE);
}
finalHolder.progressUpdate.setProgress(item.getProgress());
return row;
}
static class ViewHolder {
ImageView image;
ProgressBar progressUpdate;
ImageView deleteFileUploaded;
ImageView play;
}
public void updateListFileToUpdate(List<Upload> listFileToUpload) {
this.listFileToUpload = listFileToUpload;
}
#Override
public int getCount() {
return listFileToUpload.size();
}
#Override
public Upload getItem(int location) {
return listFileToUpload.get(location);
}
#Override
public long getItemId(int position) {
return 0;
}
}
My ImageLoader class-------------------->
private Bitmap decodeFile(File f){
try {
//decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
//Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE=Wall.width;
final int REQUIRED_SIZE1=Wall.height;
// final int REQUIRED_SIZE=250;
//
int width_tmp=o.outWidth, height_tmp=o.outHeight;
int scale=1;
// while(o.outWidth/scale/2>=REQUIRED_SIZE && o.outHeight/scale/2>=REQUIRED_SIZE)
//// scale*=2;
while(true){
if((width_tmp/2<REQUIRED_SIZE)||(height_tmp/2<REQUIRED_SIZE1))
break;
width_tmp/=2;
height_tmp/=2;
scale*=2;
}
//decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
o2.inSampleSize=scale;
o2.inJustDecodeBounds = false;
// o2.inSampleSize=2;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {}
return null;
}
I want to display the facebook wall stream in my application using graph api.
The wall stream consists of following things 1)profile picture
2)name ,posted message,posted image
3)Like,Comment options
I got the data from facebook graph api
https://graph.facebook.com/me/home?access_token="+accesstoken;
In this I got data of page1 and I used "paging" to get the data of second page and same for getting third page.
But when I tried to display the first page,because of more images I am getting
Bitmap size exceeds VM Budget error:Out of Memory error
I want to know, how the other facebook applications managing this issue,I observed that they are loading only less number of records at a time.How to do such things,if I got the data in pagewise?
public class Wall extends Activity {
private Button btnSettings,btnLogout,btnUpdate,btnWall,btnCheckin,btnPubfinder,btnCamera;
public String accesstoken,wallres,str_likevariable="",webserv,currentweb;
protected static JSONArray jsonArray;
JSONObject jsonObject = null;
MyProgressDialog dialog;
private PullToRefreshListView listView;
ArrayList<String> msg=new ArrayList<String>();
ArrayList<String> name=new ArrayList<String>();
ArrayList<String> id=new ArrayList<String>();
ArrayList<String> objid=new ArrayList<String>();
ArrayList<String> profimg=new ArrayList<String>();
ArrayList<String> img=new ArrayList<String>();
ArrayList<String> pic=new ArrayList<String>();
ArrayList<String> comment=new ArrayList<String>();
ArrayList<String> likes=new ArrayList<String>();
ArrayList<String> weburl=new ArrayList<String>();
ArrayList<String> like_or_unlike=new ArrayList<String>();
ArrayList<String> date=new ArrayList<String>();
ImageLoader imageLoader;
Handler mHandler;
View footerView;
private int previousTotal = 0,j=0;
public static int width,height;
public boolean loading = true,isScrolling,scroll=true,boolisLoad=true,boolDialog=true,addFooter=false;
MySimpleArrayAdapter adapter;
static {
StrictMode.setThreadPolicy( new StrictMode.ThreadPolicy.Builder().permitAll().build());
}
//onCreate
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.wall);
//To get device dimensions
android.view.WindowManager w = getWindowManager();
Display d = w.getDefaultDisplay();
width = d.getWidth();
height = d.getHeight();
System.out.println(width);
System.out.println(height);
btnSettings=(Button)findViewById(R.id.settings);
btnLogout=(Button)findViewById(R.id.logout);
btnCamera=(Button)findViewById(R.id.camera);
btnUpdate=(Button)findViewById(R.id.update);
btnWall=(Button)findViewById(R.id.wall);
btnCheckin=(Button)findViewById(R.id.checkin);
btnPubfinder=(Button)findViewById(R.id.pubfinder);
ButtonListener listener=new ButtonListener();
btnSettings.setOnClickListener(listener);
btnLogout.setOnClickListener(listener);
btnUpdate.setOnClickListener(listener);
btnWall.setOnClickListener(listener);
btnCheckin.setOnClickListener(listener);
btnPubfinder.setOnClickListener(listener);
btnCamera.setOnClickListener(listener);
//access token
accesstoken=Login.mFacebook.getAccessToken();
Log.e("accesstoken",accesstoken);
//first page webservice
webserv="https://graph.facebook.com/me/home?access_token="+accesstoken;
Log.e("firstweb",webserv);
//pullToRefresh Listview
listView= (PullToRefreshListView ) findViewById(R.id.walldata);
listView.setDivider(null);
//footer view
footerView = ((LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.listfooter, null, false);
// this.mHandler = new Handler();
listView.addFooterView(footerView);
//
// this.mHandler.postDelayed(m_Runnable,5000);
SessionStore.restore(Login.mFacebook, Wall.this);
SessionEvents.removeAllAuthListener();
listView.setOnRefreshListener(new OnRefreshListener() {
// #Override
public void onRefresh() {
// Your code to refresh the list contents goes here
scroll=true; //to keep the scroll at position where it has hits the load more data
pic.clear();
id.clear();
name.clear();
msg.clear();
img.clear();
profimg.clear();
objid.clear();
comment.clear();
weburl.clear();
adapter.clear();
likes.clear();
like_or_unlike.clear();
date.clear();
addFooter=true; // to add the footer view again after removing in pullToRefresh
previousTotal = 0;
loading = true;
listView.removeFooterView(footerView);
listView.setAdapter(null);
j=0;
webserv="https://graph.facebook.com/me/home?access_token="+accesstoken;
Log.e("inpull",webserv);
System.out.println(listView.getCount());
doInBack dob=new doInBack();
dob.execute();
System.out.println(listView.getCount());
Log.e("hi","doback called");
}
});
//
listView.setOnScrollListener(new OnScrollListener() {
private int threshold = 0;
//
public void onScrollStateChanged(AbsListView view, int scrollState) {
////
if (scrollState != 0) {
isScrolling = true;
}
else {
isScrolling = false; //To load the data when the scroll is in offstate
adapter.notifyDataSetChanged();
}
}
public void onScroll(AbsListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount)
{
// TODO Auto-generated method stub
if (loading) {
if (totalItemCount > previousTotal) {
Log.e("in loading","in load");
loading = false;
previousTotal = totalItemCount;
}
}
if (!loading && (firstVisibleItem + visibleItemCount+2) == totalItemCount+1){
System.out.println(firstVisibleItem);
System.out.println(visibleItemCount);
System.out.println(totalItemCount);
scroll=false;
Log.v("in gridview loading more","grid load");
//
doInBack dob=new doInBack();
dob.execute();
adapter.notifyDataSetChanged();
// doback(webserv);
loading = true;
}
}
// }
});
doInBack dob=new doInBack();
dob.execute();
// doback(webserv);
Log.e("hi","doback called");
}
/
private class ButtonListener implements View.OnClickListener{
public void onClick(View v) {
if(v.equals( btnSettings)){
Intent myintent=new Intent(Wall.this,Settings.class);
startActivity(myintent);
finish();
}
else if(v.equals(btnLogout)){
try {
String res=Login.mFacebook.logout(Wall.this);
Log.e("response",res);
System.out.println(res);
System.out.println(Login.mFacebook.isSessionValid());
//if(res.equals("true"))
//{
Intent in=new Intent(Wall.this,Login.class);
startActivity(in);
finish();
//}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else if(v.equals(btnUpdate)){
Update.i=0;
Intent myintent=new Intent(Wall.this,Update.class);
startActivity(myintent);
finish();
}
else if(v.equals(btnCamera)){
Intent myintent=new Intent(Wall.this,CameraActivity.class);
startActivity(myintent);
finish();
}
else if(v.equals(btnWall)){
// Intent myintent=new Intent(Wall.this,Wall.class);
// startActivity(myintent);
// finish();
}
else if(v.equals(btnCheckin)){
Intent myintent=new Intent(Wall.this,Checkin.class);
startActivity(myintent);
finish();
}
else if(v.equals(btnPubfinder)){
Intent myintent=new Intent(Wall.this,PubFinder.class);
startActivity(myintent);
finish();
}
}
}
class doInBack extends AsyncTask<URL, Integer, Long>
{
protected void onPreExecute()
{ if(boolDialog){
dialog=MyProgressDialog.show(Wall.this, null,null);
}
}
// currentweb= webserv;
#Override
protected Long doInBackground(URL... arg0) {
currentweb=webserv;
//
Log.e("hi","doback parsing");
try
{
// if(urlval>0){
wallres=UrltoValue.getValuefromUrl(currentweb);
Log.e("wallrespages",wallres);
}
JSONObject jobj1=new JSONObject(wallres);
JSONObject jobj2=jobj1.getJSONObject("paging");
webserv= jobj2.getString( "next");
jsonArray = jobj1.getJSONArray("data");
for(int i=0;i<jsonArray.length();i++){
jsonObject = jsonArray.getJSONObject(i);
if(jsonObject.has("message")||jsonObject.has("picture")) {
try{
// msg[j]=jsonObject.getString("message");
if(jsonObject.has("message"))
{
msg.add(jsonObject.getString("message"));
}
else{
msg.add("");
}
}
catch(Exception e){
e.printStackTrace();
}
try{
// msg[j]=jsonObject.getString("message");
if(jsonObject.has("picture"))
{
String firstpicture=jsonObject.getString("picture");
String secondpicture=firstpicture.replaceAll("_s.jpg", "_n.jpg");
Log.e("picurl",secondpicture);
pic.add(secondpicture);
}
else{
pic.add("");
}
}
catch(Exception e){
e.printStackTrace();
}
objid.add(jsonObject.getString("id"));
JSONObject jobj=jsonObject.getJSONObject("from");
name.add(jobj.getString("name"));
id.add(jobj.getString("id"));
if(jsonObject.getString("type").equals("checkin")){
name.set(i,jobj.getString("name")+" "+"is at"+" "+jsonObject.getString("name"));
}
Log.e("id",id[j]);
profimg.add("http://graph.facebook.com/"+id.get(j)+"/picture?type=square");
JSONObject commentjobj=jsonObject.getJSONObject("comments");
comment.add(commentjobj.getString("count"));
if(jsonObject.has("likes")) {
Log.e("likeornot","likre");
JSONObject likesjobj=jsonObject.getJSONObject("likes");
likes.add(likesjobj.getString("count"));
String postid=jsonObject.getString("id");
// graph_or_fql = "fql";
String query = "SELECT likes.user_likes FROM stream WHERE post_id = \'" + postid + "'";
// Log.d("finalThreadID", finalThreadID);
Bundle params = new Bundle();
params.putString("method", "fql.query");
params.putString("query", query);
// Utility.mAsyncRunner.request(null, params, new LikesListener());
String fqlResponse = Login.mFacebook.request(params);
System.out.println(fqlResponse);
JSONArray JOLikeresponse=new JSONArray(fqlResponse);
if(JOLikeresponse.length()!=0){
JSONObject JOLikeObject = JOLikeresponse.getJSONObject(0);
if ( JOLikeObject.has("likes")) {
String optlike,optlikesarray;
JSONObject optLikes=JOLikeObject;
JSONArray optLikesArray;
try{
optLikes = JOLikeObject.getJSONObject("likes");
optlike="like";
}
catch(Exception e){
optlike="unlike";
}
//
if(optlike.equals("like")){
if (optLikes.has("user_likes")) {
String getUserLikes = optLikes.getString("user_likes");
if (getUserLikes.equals("true")) {
like_or_unlike.add("Unlike");
} else if (getUserLikes.equals("false")) {
like_or_unlike.add("Like");
}
}
else {
like_or_unlike.add("Like");
}
} else {
like_or_unlike.add("Like");
}
}
//if likes object is not there in like response
else {
like_or_unlike.add("Like");
}
}
//if the like response Array length is zero
else {
like_or_unlike.add("Like");
}//FQL query object
}
//If likes are not there
else{
likes.add("0");
like_or_unlike.add("Like");
}
weburl.add(currentweb);
Log.e("comment", comment.get(j));
String getCreatedTime = jsonObject.getString("created_time");
SimpleDateFormat formatter = getDateFormat();
ParsePosition pos = new ParsePosition(0);
long then = formatter.parse(getCreatedTime, pos).getTime();
long now = new Date().getTime();
long seconds = (now - then)/1000;
long minutes = seconds/60;
long hours = minutes/60;
long days = hours/24;
String friendly = null;
long num = 0;
if (days > 0) {
num = days;
friendly = days + " day";
} else if (hours > 0) {
num = hours;
friendly = hours + " hour";
} else if (minutes > 0) {
num = minutes;
friendly = minutes + " minute";
} else if(seconds>0) {
num = seconds;
friendly = seconds + " second";
}
else{
friendly = "few seconds";
}
if (num > 1) {
friendly += "s";
}
String postTimeStamp = friendly.toLowerCase() + " ago";
Log.e("date",postTimeStamp );
date.add(postTimeStamp);
j++;
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Long result) {
try
{ if(addFooter){
listView.addFooterView(footerView);
}
addFooter=false;
System.out.println(scroll);
if(scroll){
adapter=new MySimpleArrayAdapter(Wall.this,R.layout.wall,pic,name,msg,id,profimg,comment,objid,weburl,likes, like_or_unlike,date);
listView.setAdapter(adapter);
listView.postDelayed(new Runnable() {
// #Override
public void run() {
listView.onRefreshComplete();
}
}, 2000);
if(boolDialog){
dialog.dismiss();
}
}
else{
// adapter=new MySimpleArrayAdapter(Wall.this,R.layout.wall,pic,name,msg,id,profimg,bitmap,comment,objid,weburl);
adapter.notifyDataSetChanged();
listView.postDelayed(new Runnable() {
// #Override
public void run() {
listView.onRefreshComplete();
}
}, 2000);
}
if(boolDialog){
dialog.dismiss();
}
}
catch(Exception e)
{
e.printStackTrace();
if(boolDialog){
dialog.dismiss();
}
}
boolDialog=false;
}
}
private static SimpleDateFormat getDateFormat() {
return new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ");
}
public class MySimpleArrayAdapter extends ArrayAdapter<String> {
private Activity context;
ArrayList<String> namear,msgar,idar,profimage,postimage,commentsnum,objectid,urlString,likescount,like_or_ulike,datesofpost;
TextView name1, message1,comments,commentsnumber, likesnumber,likes,dateofpost;
ImageView profimg,postimg;
ImageLoader imageLoader;
Bitmap[] bitdata;
// ViewHolder holder ;
// View rowView;
public MySimpleArrayAdapter(Activity c,int i,ArrayList<String> postpic, ArrayList<String> names,ArrayList<String> msg,ArrayList<String> id,ArrayList<String> proimg,ArrayList<String> comment,ArrayList<String> objid,ArrayList<String> web,ArrayList<String> likecount,ArrayList<String> unlike_or_like,ArrayList<String> dates) {
super(c, i, names);
Log.e("adapter","adap");
this.context = c;
this.namear = names;
this.msgar = msg;
this.idar = id;
this.profimage=proimg;
this.postimage=postpic;
// this.bitdata=bit;
this.commentsnum=comment;
this.objectid=objid;
this.urlString=web;
this.likescount=likecount;
this.like_or_ulike=unlike_or_like;
this.datesofpost=dates;
this.imageLoader = new ImageLoader(context);
}
// public View getView(final int position, View convertView, ViewGroup parent) {
//// View view;
// TextView title1,id,name1,dispdate,loc;
// ImageView image,delete,arrow;
// View view = convertView;
//// view = inflater.inflate(R.layout.myfav_row, parent, false);
// LayoutInflater inflator = context.getLayoutInflater();
// view = inflator.inflate(R.layout.myfav_row, null);
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// code to load images
View rowView=convertView ;
LayoutInflater inflator = getLayoutInflater();
rowView = inflator.inflate(R.layout.walldata, null);
name1 = (TextView) rowView.findViewById(R.id.name);
message1 = (TextView) rowView.findViewById(R.id.msg);
profimg= (ImageView) rowView.findViewById(R.id.profile_pic);
postimg= (ImageView) rowView.findViewById(R.id.picpost);
comments = (TextView) rowView.findViewById(R.id.comment);
likes = (TextView) rowView.findViewById(R.id.like);
commentsnumber = (TextView) rowView.findViewById(R.id.commentnumber);
likesnumber = (TextView) rowView.findViewById(R.id.likesnumber);
dateofpost = (TextView) rowView.findViewById(R.id.datepost);
// rowView.setTag(holder);
Log.e("user",idar.get(position));
Log.e("adapter","adap");
name1.setText(namear.get(position));
if(msgar.get(position)!=""){
message1.setText(msgar.get(position));
}
else
{
message1.setVisibility(View.GONE);
}
if(!isScrolling){
if(!postimage.get(position).equals(""))
{try{
imageLoader.DisplayImage(postimage.get(position).replace(" ", "%20"), postimg) ;
// Bitmap b= imageLoader.getBitmap(postimage.get(position));
// postimg.setImageBitmap(b);
}
catch(Exception e){
e.printStackTrace();
}
}
else
{
postimg.setVisibility(View.GONE);
}
}
try{
imageLoader.DisplayImage(profimage.get(position).replace(" ", "%20"), profimg) ;
}
catch(Exception e){
e.printStackTrace();
}
dateofpost.setText(datesofpost.get(position));
commentsnumber.setText(commentsnum.get(position));
likesnumber.setText(likescount.get(position));
likes.setText(like_or_ulike.get(position));
likes.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// if(likes.getText().toString().equals("Like")){
TextView t=(TextView)v;
TextView likescountmodify = null;
View parent = (View) t.getParent();
if (parent != null) {
likescountmodify = (TextView)parent.findViewById(R.id.likesnumber);
}
int i= Integer.parseInt(likescount.get(position));
if(like_or_ulike.get(position).equals("Like")){
Log.e("inlike","like");
like_or_ulike.set(position, "Unlike");
t.setText(like_or_ulike.get(position));
UrltoValue.getValuefromUrl("https://graph.facebook.com/"+objectid.get(position)+"/likes?access_token="+accesstoken+"&method="+"post");
// listView.getAdapter().getItemAt(position);
j=i+1;
String s=Integer.toString(j);
likescount.set(position, s);
likescountmodify.setText(likescount.get(position));
}
else{
Log.e("unlike","unlike");
like_or_ulike.set(position, "Like");
t.setText(like_or_ulike.get(position));
UrltoValue.getValuefromUrl("https://graph.facebook.com/"+objectid.get(position)+"/likes?access_token="+accesstoken+"&method="+"DELETE");
j=i-1;
String s=Integer.toString(j);
likescount.set(position, s);
likescountmodify.setText(likescount.get(position));
}
}
});
comments.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myintent=new Intent(Wall.this,Comments.class);
myintent.putExtra("name", namear.get(position));
myintent.putExtra("profimg", profimage.get(position));
myintent.putExtra("message", msgar.get(position));
myintent.putExtra("postpic", postimage.get(position));
myintent.putExtra("objectid", objectid.get(position));
myintent.putExtra("commentsnum",commentsnum.get(position));
myintent.putExtra("webservice", urlString.get(position));
startActivity(myintent);
finish();
}
});
return rowView;
}
}
please help
Thanks in advance
They might be caching the records or posts and they display(load) records visible to the user at that instant. on how to do this, check out this sample application from developer.android.com ->
displaying-bitmaps Efficiently.
You should try to limit the size of the Bitmaps that you show close to the size of the image view so that you don't waste memory by having large images in memory when you actually want to show a lower resolution image. I usually use this function to resize an image file to a size closer to the one that I want.
// decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f) {
try {
// decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
// TODO: Do something
}
return null;
}
// Use Option class instead of BitmapFactory.Options
Options opts = new Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, opts);
Log.e("optwidth",opts.outWidth+"");
opts.inJustDecodeBounds = false;
if(opts.outWidth>500){
opts.inSampleSize = 4;
mBitmap = BitmapFactory.decodeFile(path, opts);
}
else mBitmap = BitmapFactory.decodeFile(path, opts);
Note: It can degrades the quality of Image but surely it can remove your Out of memory error for bitmap according to my knowledge. for more details check this link: Handling large Bitmaps