I have seen many answers on this issue which has not worked so far for me, the best option I got was using a Picasso to solve this, I have imported the .jar but am getting an error on the code I was told to use, I get an error on this(context) in the following line of code, say (context) cannot be resolved to a variable
Picasso.with(context).load(myBitmap).into(imageView);
This is the lines of code that generates the error, which I intend solving using Picasso
File imgFile = new File(data.get(position).get("path"));
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
imageView.setImageBitmap(myBitmap);
This is my full code below
public class WidgetActivity extends Activity {
GridView grid;
Matrix matrix = new Matrix();
Bitmap rotateimage;
ArrayList<HashMap<String, String>> maplist = new ArrayList<HashMap<String,String>>();
LocalStorageHandler notedb;
ImageView iv_notes;
EditText content;
LinearLayout grid_layout;
AppWidgetManager appWidgetManager;
int n;
Intent i;
int s;
String[] tcolor;
public String path = "", name = "", color = "";
public void onCreate(Bundle os) {
super.onCreate(os);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.dialog_shownotes);
notedb = new LocalStorageHandler(WidgetActivity.this);
grid = (GridView) findViewById(R.id.grid);
iv_notes = (ImageView) findViewById(R.id.iv_note);
content = (EditText) findViewById(R.id.content);
grid_layout = (LinearLayout) findViewById(R.id.grid_layout);
i = getIntent();
n = i.getIntExtra("currentWidgetId", 1);
new getlist().execute();
}
class getlist extends AsyncTask<String, String, String> {
ArrayList<HashMap<String, String>> maplist = new ArrayList<HashMap<String, String>>();
#Override
public void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg) {
ArrayList<String> filepaths = new ArrayList<String>();
ArrayList<String> filenames = new ArrayList<String>();
Cursor dbCursor = notedb.get();
if (dbCursor.getCount() > 0) {
int noOfScorer = 0;
dbCursor.moveToFirst();
while ((!dbCursor.isAfterLast())
&& noOfScorer < dbCursor.getCount()) {
noOfScorer++;
try {
HashMap<String, String> items = new HashMap<String, String>();
filepaths.add(Environment.getExternalStorageDirectory()
+ "/360notes/" + dbCursor.getString(2));
filenames.add(dbCursor.getString(3));
items.put("path",
Environment.getExternalStorageDirectory()
+ "/360notes/" + dbCursor.getString(2));
items.put("name", dbCursor.getString(3));
items.put("time", dbCursor.getString(1));
items.put("id", dbCursor.getString(0));
items.put("color", dbCursor.getString(4));
maplist.add(items);
} catch (Exception e) {
e.printStackTrace();
}
dbCursor.moveToNext();
}
}
return null;
}
#Override
protected void onPostExecute(String unused) {
if (maplist.size() > 0) {
grid.setAdapter(new GridViewImageAdapter(WidgetActivity.this,
maplist));
}
}
}
public class GridViewImageAdapter extends BaseAdapter {
private Activity _activity;
ArrayList<String> _filenames = new ArrayList<String>();
private ArrayList<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();
public GridViewImageAdapter(Activity activity,
ArrayList<HashMap<String, String>> items) {
this._activity = activity;
data = items;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
LayoutInflater inflate = (LayoutInflater) _activity
.getSystemService(_activity.LAYOUT_INFLATER_SERVICE);
convertView = inflate.inflate(R.layout.show_image, null);
ImageView imageView = (ImageView) convertView
.findViewById(R.id.imgScreen);
TextView title = (TextView) convertView.findViewById(R.id.title);
try {
String[] tcolor = data.get(position).get("name").split(" / ");
title.setText(tcolor[0].trim());
title.setTextColor(Color.parseColor(tcolor[1].trim()));
if (tcolor[2].trim().equals("0")) {
String text = title.getText().toString();
SpannableString span = new SpannableString(text);
span.setSpan(new UnderlineSpan(), 0, span.length(), 0);
// title.setText(span);
} else if (tcolor[2].trim().equals("3")) {
// title.setTypeface(null, Typeface.BOLD);
String text = title.getText().toString();
SpannableString span = new SpannableString(text);
span.setSpan(new UnderlineSpan(), 0, span.length(), 0);
// title.setText(span);
} else if (tcolor[2].trim().equals("4")) {
// title.setTypeface(null, Typeface.ITALIC);
String text = title.getText().toString();
SpannableString span = new SpannableString(text);
span.setSpan(new UnderlineSpan(), 0, span.length(), 0);
// title.setText(span);
} else if (tcolor[2].trim().equals("1")) {
// title.setTypeface(null, Typeface.BOLD);
String text = title.getText().toString();
SpannableString span = new SpannableString(text);
span.removeSpan(text);
} else if (tcolor[2].trim().equals("2")) {
// title.setTypeface(null, Typeface.ITALIC);
String text = title.getText().toString();
SpannableString span = new SpannableString(text);
span.removeSpan(text);
} else {
String text = title.getText().toString();
SpannableString span = new SpannableString(text);
span.removeSpan(text);
}
} catch (IndexOutOfBoundsException e) {
// TODO: handle exception
}
// TODO: handle exception
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
File imgFile = new File(data.get(position).get("path"));
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
imageView.setImageBitmap(myBitmap);
/*if (myBitmap != null && !myBitmap.isRecycled()) {
myBitmap.recycle();
myBitmap = null;
}*/
//myBitmap.recycle();
//myBitmap = null;
Picasso.with(context).load(myBitmap).into(imageView);
grid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
grid.setVisibility(View.GONE);
// grid_layout.setVisibility(View.VISIBLE);
s = position;
path = data.get(position).get("path");
try {
tcolor = data.get(position).get("name").split(" / ");
name = tcolor[0].trim();
color = tcolor[1].trim();
} catch (IndexOutOfBoundsException e) {
name = "";
color = "#000000";
}
appWidgetManager = AppWidgetManager
.getInstance(WidgetActivity.this);
UnreadWidgetProvider.updateWidget(WidgetActivity.this,
appWidgetManager, n, path,
data.get(position).get("name"), color, s);
finish();
}
});
return convertView;
}
}
public void images(String path, String name, String color) {
try {
Bitmap bm;
try {
bm = decodeSampledBitmapFromResource(path);
ExifInterface exifReader = new ExifInterface(path);
int orientation = exifReader.getAttributeInt(
ExifInterface.TAG_ORIENTATION, -1);
if (orientation == ExifInterface.ORIENTATION_NORMAL) {
matrix.postRotate(360);
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
// matrix.postRotate(90);
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
// matrix.postRotate(180);
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
// matrix.postRotate(270);
} else if (orientation == ExifInterface.ORIENTATION_UNDEFINED) {
// matrix.postRotate(90);
} else {
}
rotateimage = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
bm.getHeight(), matrix, true);
iv_notes.setImageBitmap(rotateimage);
content.setText(name);
content.setFocusable(false);
try {
String[] tcolor = name.split(" / ");
content.setText(tcolor[0].trim());
content.setTextColor(Color.parseColor(tcolor[1].trim()));
if (tcolor[2].trim().equals("0")) {
String text = content.getText().toString();
SpannableString span = new SpannableString(text);
span.setSpan(new UnderlineSpan(), 0, span.length(), 0);
// content.setText(span);
} else if (tcolor[2].trim().equals("3")) {
// content.setTypeface(null, Typeface.BOLD);
String text = content.getText().toString();
SpannableString span = new SpannableString(text);
span.setSpan(new UnderlineSpan(), 0, span.length(), 0);
// content.setText(span);
} else if (tcolor[2].trim().equals("4")) {
// content.setTypeface(null, Typeface.ITALIC);
String text = content.getText().toString();
SpannableString span = new SpannableString(text);
span.setSpan(new UnderlineSpan(), 0, span.length(), 0);
// content.setText(span);
} else if (tcolor[2].trim().equals("1")) {
// content.setTypeface(null, Typeface.BOLD);
String text = content.getText().toString();
SpannableString span = new SpannableString(text);
span.removeSpan(text);
} else if (tcolor[2].trim().equals("2")) {
// content.setTypeface(null, Typeface.ITALIC);
String text = content.getText().toString();
SpannableString span = new SpannableString(text);
span.removeSpan(text);
} else {
String text = content.getText().toString();
SpannableString span = new SpannableString(text);
span.removeSpan(text);
}
} catch (IndexOutOfBoundsException e) {
// TODO: handle exception
}
grid_layout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int i = grid.getCount();
Intent intentAlarm = new Intent(WidgetActivity.this,
WriteNotesActivity.class);
intentAlarm.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
intentAlarm.putExtra("max", s);
startActivity(intentAlarm);
finish();
}
});
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
// finish();
}
}
public static Bitmap decodeSampledBitmapFromResource(String resId) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, 400, 300);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(resId, options);
}
public static 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;
}
}
This might help someone out there after several hours without an answer to this. I found a way of solving this without using Picasso in handling the outOfMemoryError. I added this line of code in my Manifest file.
android:largeHeap="true"
I added this to the entire application here as below:-
<application
android:icon="#drawable/ic_launcher"
android:largeHeap="true"
android:label="#string/app_name" >
android:largeHeap is the instrument for increasing your allocated memory to app.
EDIT:
well, you are using too much memory. remove those 3 lines of code :
File imgFile = new File(data.get(position).get("path"));
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
imageView.setImageBitmap(myBitmap);
simply, you are assigning too much space to these instances and your phone runs out of memory. Just use my response and consider logging the file path so you can possibly use that without creating another file.
i think you used wrong implementation. Probably the context is not adressing correctly and therefore, i would personally use "this" instead. And for loading resources, their guide provides us with three implementations, see below:
pass drawable
Picasso.with(context).load(R.drawable.landing_screen).into(imageView1);
pass uri
Picasso.with(context).load("file:///android_asset/DvpvklR.png").into(imageView2);
pass file
Picasso.with(context).load(new File(...)).into(imageView3);
so therefore i would decode the image using this code:
Picasso.with(this).load(new File(data.get(position).get("path"))).into(imageView);
Related
I want to create the image of the barcode/QR code etc on my app. I have searched a lot and have found different libraries to do this task but since I am already using Zxing so i would like to work in it.
Following is the code that I have writen:
This is my Scanner Activity class:
public void handleResult(Result rawResult) {
// Do something with the result here
Log.v(TAG, rawResult.getText()); // Prints scan results
Toast.makeText(SimpleScannerActivity.this, rawResult.toString() + " WOW scanned", Toast.LENGTH_LONG).show();
Toast.makeText(SimpleScannerActivity.this, rawResult.getBarcodeFormat().toString(), Toast.LENGTH_LONG).show();
Log.v(TAG, rawResult.getBarcodeFormat().toString()); // Prints the scan format (qrcode, pdf417 etc.)
//Intent scanScreenResult= new Intent("com.aaa.fyp.ScanResultScreen");
setFormat(rawResult);
Intent nextScreen = new Intent("com.aaa.fyp.ScanResultScreen");
nextScreen.putExtra("barcode",rawResult.toString());
nextScreen.putExtra("format", rawResult.getBarcodeFormat().toString());
finish();
startActivity(nextScreen);
}
public void setFormat(Result result){
r=result.getBarcodeFormat();
System.out.println("============================== setformat main"+ r);
}
public BarcodeFormat getFormat(){
System.out.println("============================== getformat main"+ r);
return r;
}
Using the results from the above activity in ScanResultScreen activity.
public class ScanResultScreen extends SimpleScannerActivity {
ImageView scanned;
TextView bc;
TextView f;
String Barcode;
String format;
BarcodeFormat form;
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
setContentView(R.layout.scan_screen_with_button);
ViewGroup layout = (ViewGroup) findViewById(R.id.scanScreenWithButton);
setContentView(layout);
Intent prevScreen = getIntent(); // gets the previously created intent
Barcode=prevScreen.getStringExtra("barcode");
bc= (TextView)findViewById(R.id.barcode_label);
bc.setText(Barcode);
format=prevScreen.getStringExtra("format");
f=(TextView) findViewById(R.id.format_label);
f.setText(prevScreen.getStringExtra("format").toString());
SimpleScannerActivity obj=new SimpleScannerActivity();
form=obj.getFormat();
d=(TextView)findViewById(R.id.date_label);
String formattedDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());
d.setText(formattedDate);
Bitmap bitmap = null;
ImageView iv = new ImageView(this);
try {
bitmap = encodeAsBitmap(Barcode, form, 600, 300);
iv.setImageBitmap(bitmap);
} catch (WriterException e) {
e.printStackTrace();
}
layout.addView(iv);
}
private static final int WHITE = 0xFFFFFFFF;
private static final int BLACK = 0xFF000000;
Bitmap encodeAsBitmap(String contents, BarcodeFormat format, int img_width, int img_height) throws WriterException {
String contentsToEncode = contents;
if (contentsToEncode == null) {
return null;
}
Map<EncodeHintType, Object> hints = null;
String encoding = guessAppropriateEncoding(contentsToEncode);
if (encoding != null) {
hints = new EnumMap<EncodeHintType, Object>(EncodeHintType.class);
hints.put(EncodeHintType.CHARACTER_SET, encoding);
}
MultiFormatWriter writer = new MultiFormatWriter();
BitMatrix result;
try {
result = writer.encode(contentsToEncode, format, img_width, img_height, hints);
} catch (IllegalArgumentException iae) {
// Unsupported format
return null;
}
int width = result.getWidth();
int height = result.getHeight();
int[] pixels = new int[width * height];
for (int y = 0; y < height; y++) {
int offset = y * width;
for (int x = 0; x < width; x++) {
pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}
private static String guessAppropriateEncoding(CharSequence contents) {
// Very crude at the moment
for (int i = 0; i < contents.length(); i++) {
if (contents.charAt(i) > 0xFF) {
return "UTF-8";
}
}
return null;
}
Now I am getting a Null value in the variable "form". Even though I am able to get the barcodeFormat in my second activity by passing it through intent but it's in the type String. Whereas the built-in methods that I am using here requires it in BarcodeFormat that is available in Zxing.
Help!!
BarcodeFormat is an enum type. If you want to pass a String value, you have to convert it to BarcodeFormat.
For example, passing a barcode format "AZTEC":
BarcodeFormat format = Enum.valueOf(BarcodeFormat.class, "AZTEC");
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 use custom ArrayAdapter to populate listview.
I use Picasso to load images, before loading image I calculate height and width for each image. Thus dynamic ImageView has different height and width.
When I scroll up the listview, everything is smooth. But when I scroll the listview down, list starts to jump, when it comes to the rows with images.
I think, it caused by listview elements recycle, it forgets dynamic imageviews heights and produce this jumping effect when it recalculating imageviews again. I attach my dynamic imageview to Holder, but it doesn't help.
Part of my adapter looks like this:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ChatMessageElement el = list.get(position);
ViewHolder holder = null;
NewMessagesLabelHolder labelHolder = null;
if (convertView == null) {
convertView = el.getView(inflater, parent);
if (el.isMessage()) {
holder = new ViewHolder();
holder.messageLayout = (RelativeLayout) convertView.findViewById(R.id.message_container);
holder.messageContent = (LinearLayout) convertView.findViewById(R.id.message_content);
holder.bottomIndicator = (LinearLayout) convertView.findViewById(R.id.bottom_indicators);
holder.dateTextView = (TextView) convertView.findViewById(R.id.message_date);
holder.timeAgo = (TextView) convertView.findViewById(R.id.time_ago);
holder.nameTextView = (TextView) convertView.findViewById(R.id.user_name);
convertView.setTag(holder);
}
} else {
if (el.isMessage()) {
holder = (ViewHolder) convertView.getTag();
}
}
if (el.isMessage()) {
Message currentMessage = (Message) el;
drawMessage(holder, currentMessage, position);
}
return convertView;
}
private void drawMessage(ViewHolder holder, Message message, int position) {
String date = message.getCreatedAt();
String formattedDate = Helper.getInstance().formatDate("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "HH:mm", date);
String userName = message.getUserName();
holder.likesLabelImageView.setVisibility(View.GONE);
holder.likesCountTextView.setVisibility(View.GONE);
holder.nameTextView.setText(userName);
holder.dateTextView.setText(formattedDate);
if (message.isLiked()) {
holder.likesCountTextView.setText(Integer.toString(message.getLikesCount()));
holder.likesCountTextView.setVisibility(View.VISIBLE);
holder.likesLabelImageView.setVisibility(View.VISIBLE);
}
List<MessageComponent> messageComponentList;
messageComponentList = message.getMessageComponents();
drawMessageContent(holder, messageComponentList, message);
holder.nameTextView.setTag(position);
holder.avatarImageView.setTag(position);
holder.nameTextView.setOnClickListener(userClickListener);
holder.avatarImageView.setOnClickListener(userClickListener);
// hang empty onLingClickListener to display context menu when
// long click on whole message
holder.nameTextView.setOnLongClickListener(longClickListener);
holder.avatarImageView.setOnLongClickListener(longClickListener);
}
private void drawMessageContent(ViewHolder holder, final List<MessageComponent> messageComponentList, final Message msg) {
holder.messageContent.removeAllViewsInLayout();
int messageComponentListSize = messageComponentList.size();
for (final MessageComponent messageComponent : messageComponentList) {
messageComponentListSize--;
if (messageComponentListSize == 0)
iAmLast = true;
final String type = messageComponent.getType();
if (type.equals(MessageComponent.MESSAGE_COMPONENT_TEXT_TYPE)) {
TextView textView = new TextView(context);
textView.setText(messageComponent.getText());
setViewBackground(textView, msg);
//reset margins for texts, caused by margin changes for images
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) holder.bottomIndicator.getLayoutParams();
params.setMargins(45, -82, 0, 0);
holder.bottomIndicator.setLayoutParams(params);
holder.messageContent.addView(textView);
}
if (type.equals(MessageComponent.MESSAGE_COMPONENT_IMAGE_TYPE)) {
ViewGroup.LayoutParams params = new ActionBar.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
thumbHeight
);
final RoundedImageView imageView = new RoundedImageView(context);
imageView.setPadding(20, 0, 20, 20);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setCornerRadius(15.0f);
mHandler.post(new Runnable() {
#Override
public void run() {
drawPreview(messageComponent, imageView);
}
});
imageView.setLayoutParams(params);
// hang empty onLingClickListener to display context menu when
// long click on whole message
imageView.setOnLongClickListener(longClickListener);
final RelativeLayout mediaContainer = new RelativeLayout(context);
mediaContainer.addView(imageView);
}
}
}
// Calculates restricted dimensions with a maximum of $goal_width by $goal_height
private ImageSize resize_dimensions(float goal_width, float goal_height, float width, float height) {
float ratio = Math.min(goal_width/width, goal_height/height);
int nwidth = Math.round(width*ratio);
int nheight = Math.round(height*ratio);
if(nwidth>nheight*2)
nheight = 400;
if(nheight>nwidth*2)
nwidth = 600;
ImageSize imageSize = new ImageSize(nwidth, nheight);
return imageSize;
}
private void drawPreview(MessageComponent messageComponent, final ImageView imageView) {
String type = messageComponent.getType();
String mediaPath = messageComponent.getMediaPath();
String thumbPath = messageComponent.getThumbPath();
String thumbUrl = messageComponent.getThumbUrl();
String videoThumbPath = messageComponent.getVideoThumbPath();
Uri uri = null;
if (type.equals(MessageComponent.MESSAGE_COMPONENT_IMAGE_TYPE)) {
if (!TextUtils.isEmpty(mediaPath)) {
uri = Uri.parse("file://" + mediaPath);
File file = new File(uri.getPath());
if (file.exists()) {
resizeAndLoadThumbnail(uri, imageView);
return;
}
}
if (!TextUtils.isEmpty(thumbPath)) {
uri = Uri.parse("file://" + mediaPath);
File file = new File(uri.getPath());
if (file.exists()) {
resizeAndLoadThumbnail(uri, imageView);
return;
}
}
if (thumbUrl != null) {
uri = Uri.parse(thumbUrl);
}
if (uri != null) {
resizeAndLoadThumbnail(uri, imageView);
return;
}
}
}
private void resizeAndLoadThumbnail(Uri uri, final ImageView imageView) {
Picasso.with(context).load(uri).into(new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
ImageSize imgSize = resize_dimensions(900, 900, width, height);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
imgSize.width,
imgSize.height
);
imageView.setLayoutParams(params);
imageView.setImageBitmap(bitmap);
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
}
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