JustPaste.it
User avatar
@anonymous · Jan 14, 2015

public class TestDrawableClass {

private TextView htmlTextView;
private SpannableStringBuilder htmlSpannable;
public Context context;
public String fullHtmlCode;
public String path;
public String filename;
public File universalFile;
public ImageView imageToDraw;
public RichPost richPost;

public Bitmap singleImage = null;
public Bitmap[] multiImages = null;
int positionInArray = 0;

public TestDrawableClass(String htmlCode, TextView tv, Context context, ImageView imageToDraw, RichPost richPost) {
this.fullHtmlCode = htmlCode;
this.htmlTextView = tv;
this.context = context;
this.imageToDraw = imageToDraw;
this.richPost = richPost;
Log.w("in constructor ", "1");
// first parse the html
// replace getHtmlCode() with whatever generates/fetches your html
Spanned spanned = Html.fromHtml(richPost.getHtmlCode());

// we need a SpannableStringBuilder for later use
if (spanned instanceof SpannableStringBuilder) {
// for now Html.fromHtml() returns a SpannableStringBuiler
// so we can just cast it
htmlSpannable = (SpannableStringBuilder) spanned;
} else {
// but we have a fallback just in case this will change later
// or a custom subclass of Html is used
new SpannableStringBuilder(spanned);
}

// now we can call setText() on the next view.
// this won't show any images yet
Log.w("in constructor ", "2");
// insertTempImage();
try {
getImagesAttach();
} catch (ParseException e) {
e.printStackTrace();
}
htmlTextView.setText(htmlSpannable);

// next we start a AsyncTask that loads the images
new displayAllRichText().execute();
// new ImageLoadTask().execute(); -- old one that works.

// ...
}

private void getImagesAttach() throws ParseException {


if (richPost.getPhotosArray() != null) {
Log.w("getPhotoArray is NOT NULL", "now1");
multiImages = new Bitmap[richPost.getPhotosArray().size()];
Log.w("getPhotoArray is NOT NULL", " MultiImgSize " + multiImages.length);

for (int i = 0; i < richPost.getPhotosArray().size(); i++) {
ParseFile temp = (ParseFile) richPost.getPhotosArray().get(i);
byte[] file = temp.getData();
Bitmap tempBitmap = BitmapFactory.decodeByteArray(file, 0, file.length);
multiImages[i] = tempBitmap;
}
}
}

private void insertTempImage() {
for (ImageSpan img : htmlSpannable.getSpans(0, htmlSpannable.length(), ImageSpan.class)) {

String fileName = "tblock.png";
Drawable d = context.getResources().getDrawable(R.drawable.tblock);
// Drawable d = new BitmapDrawable(context.getResources(),
// fileName);
d.setBounds(0, 0, 1, 1);

ImageSpan newImg = new ImageSpan(d, img.getSource());

// find the position of the old ImageSpan
int start = htmlSpannable.getSpanStart(img);
int end = htmlSpannable.getSpanEnd(img);

// remove the old ImageSpan
htmlSpannable.removeSpan(img);
// add the new ImageSpan
htmlSpannable.setSpan(newImg, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

htmlTextView.setText(htmlSpannable);

}
}

// Going to attempt a whole new class to handle the existing images and
// everything
private class displayAllRichText extends AsyncTask<Void, ImageSpan, Void> {
DisplayMetrics metrics = new DisplayMetrics();

@Override
protected void onPreExecute() {
((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(metrics);
}

@Override
protected Void doInBackground(Void... params) {
for (ImageSpan img : htmlSpannable.getSpans(0, htmlSpannable.length(), ImageSpan.class)) {

publishProgress(img);
}
return null;
}

@Override
protected void onProgressUpdate(ImageSpan... values) {

Log.w("in aysnc ", "onProgressUpdate single image: " + singleImage);
Log.w("in aysnc ", "onProgressUpdate multiple image: " + multiImages);
// save ImageSpan to a local variable just for convenience
ImageSpan img = values[0];

if (singleImage != null) {
Log.w("Single image doesn't equal null", "now");
Drawable d = new BitmapDrawable(context.getResources(), singleImage);
Log.w("Single image doesn't equal null - create drawable", "now: " + d);
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
int densityMetrics = (int) metrics.density;
int screenWidth = metrics.widthPixels;
int getInstricWidth = d.getIntrinsicWidth();
int getInstricHeight = d.getIntrinsicHeight();

Log.w("Single image doesn't equal null - some values", "now: " + d.getIntrinsicWidth() + " screenWidth: " + screenWidth);
if (d.getIntrinsicWidth() > screenWidth) {
d.setBounds(0, 0, 500, 500);
} else {
int right = ((screenWidth - getInstricWidth) / densityMetrics);
int left = screenWidth - right;
d.setBounds(right, 0, left, getInstricHeight);
}

// now we create a new ImageSpan
Log.w("Single image doesn't equal null - create imagespan", "now" + img.getSource());
ImageSpan newImg = new ImageSpan(d, img.getSource());

// find the position of the old ImageSpan
int start = htmlSpannable.getSpanStart(img);
int end = htmlSpannable.getSpanEnd(img);

// remove the old ImageSpan
htmlSpannable.removeSpan(img);
// add the new ImageSpan
htmlSpannable.setSpan(newImg, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

htmlTextView.setText(htmlSpannable);
}

if(multiImages != null){
Log.w("in aysnc ", "multiimages in not null: " + multiImages.length);
//for (int i = 0; i < multiImages.length; i++) {

Drawable d = new BitmapDrawable(context.getResources(), multiImages[positionInArray]);
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
int densityMetrics = (int) metrics.density;
int screenWidth = metrics.widthPixels;
int getInstricWidth = d.getIntrinsicWidth();
int getInstricHeight = d.getIntrinsicHeight();

if (d.getIntrinsicWidth() > screenWidth) {
d.setBounds(0, 0, 500, 500);
} else {
int right = ((screenWidth - getInstricWidth) / densityMetrics);
int left = screenWidth - right;
d.setBounds(right, 0, left, getInstricHeight);
}
ImageSpan newImg = new ImageSpan(d, img.getSource());
int start = htmlSpannable.getSpanStart(img);
int end = htmlSpannable.getSpanEnd(img);

htmlSpannable.removeSpan(img);
htmlSpannable.setSpan(newImg, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

htmlTextView.setText(htmlSpannable);

if(positionInArray <= multiImages.length){
positionInArray++;
}
//}
}
}

}

private class ImageLoadTask extends AsyncTask<Void, ImageSpan, Void> {
File temporyFileType;
DisplayMetrics metrics = new DisplayMetrics();

@Override
protected void onPreExecute() {
Log.w("in aysnc ", "preexecute");
// we need this to properly scale the images later
((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(metrics);

imageToDraw.setVisibility(View.GONE);

}

@Override
protected Void doInBackground(Void... params) {
// iterate over all images found in the html
Log.w("in aysnc ", "doInBackground");
for (ImageSpan img : htmlSpannable.getSpans(0, htmlSpannable.length(), ImageSpan.class)) {


// Lets try straight drawable to save converstion
try {
universalFile = saveImageFile(img.getSource());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

// we use publishProgress to run some code on the
// UI thread to actually show the image
// -> onProgressUpdate()

// if(complete == true){
publishProgress(img);

}

return null;

}

public boolean handleTheDownloadAndSave(ImageSpan img) {
Log.d("im the download file ", " " + img.getSource());

String urldisplay = img.getSource();
Drawable mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
// mIcon11 = BitmapFactory.decodeStream(in);
mIcon11 = Drawable.createFromStream(in, "src");
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
path = saveToInternalSorage(mIcon11);

return true;

}

@Override
protected void onProgressUpdate(ImageSpan... values) {

Log.w("in aysnc ", "onProgressUpdate");
// save ImageSpan to a local variable just for convenience
ImageSpan img = values[0];

File cache = getImageFile(img);

if (universalFile.isFile()) {
Log.i("WE HAVE A FILE IN THE CAHCE", " NOW");
} else {
Log.i("CACHE IS STILL NOT WORKING ", " NOW ");
}

// if the file exists, show it
if (cache.isFile()) {

// first we need to get a Drawable object
Drawable d = new BitmapDrawable(context.getResources(), cache.getAbsolutePath());

int width, height;
int originalWidthScaled = (int) (d.getIntrinsicWidth() * metrics.density);
int originalHeightScaled = (int) (d.getIntrinsicHeight() * metrics.density);
if (originalWidthScaled > metrics.widthPixels) {
height = d.getIntrinsicHeight() * metrics.widthPixels / d.getIntrinsicWidth();
width = metrics.widthPixels;
} else {
height = originalHeightScaled;
width = originalWidthScaled;
}

DisplayMetrics metrics = context.getResources().getDisplayMetrics();
int densityMetrics = (int) metrics.density;
int screenWidth = metrics.widthPixels;
int getInstricWidth = d.getIntrinsicWidth();
int getInstricHeight = d.getIntrinsicHeight();

int pixels = (int) denPixel(context);

if (d.getIntrinsicWidth() > screenWidth) {

} else {
int right = ((screenWidth - getInstricWidth) / densityMetrics);
int left = screenWidth - right;
d.setBounds(right, 0, left, getInstricHeight);
}

 

// now we create a new ImageSpan
ImageSpan newImg = new ImageSpan(d, img.getSource());

// find the position of the old ImageSpan
int start = htmlSpannable.getSpanStart(img);
int end = htmlSpannable.getSpanEnd(img);

// remove the old ImageSpan
htmlSpannable.removeSpan(img);
// add the new ImageSpan
htmlSpannable.setSpan(newImg, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

Log.d("Getting the value of iamgeToDraw ", " " + imageToDraw);

// finally we have to update the TextView with our
// updates Spannable to display the image
htmlTextView.setText(htmlSpannable);

// }
}
}
}

public static float denPixel(Context c) {
DisplayMetrics metrics = c.getResources().getDisplayMetrics();
return metrics.density;
}

public static int screenWidthPixels(Context c) {
DisplayMetrics metrics = c.getResources().getDisplayMetrics();
return metrics.widthPixels;
}

public static int screenHeightPixels(Context c) {
DisplayMetrics metrics = c.getResources().getDisplayMetrics();
return metrics.heightPixels;
}

private File saveImageFile(String aFileName) throws IOException {
// TODO Auto-generated method stub
final String cachePath = context.getCacheDir().getPath();
File myDisCacheFilePath;
myDisCacheFilePath = new File(cachePath);

// File myDisCacheFile = new File(myDisCacheFilePath + File.separator +
// aFileName);
File myDisCacheFile = new File(myDisCacheFilePath + File.separator + aFileName);
myDisCacheFile.getParentFile().mkdirs(); // Make it a directroy.

// Start the download of the file.
URL u = new URL(aFileName);
URLConnection uc = u.openConnection();
String contentType = uc.getContentType();
int contentLength = uc.getContentLength();
if (contentType.startsWith("text/") || contentLength == -1) {
throw new IOException("This is not a binary file.");
}
// Time to do the saving of the fien
InputStream raw = uc.getInputStream();
InputStream in = new BufferedInputStream(raw);
byte[] data = new byte[contentLength];
int bytesRead = 0;
int offset = 0;
while (offset < contentLength) {
bytesRead = in.read(data, offset, data.length - offset);
if (bytesRead == -1)
break;
offset += bytesRead;
}
in.close();

if (offset != contentLength) {
throw new IOException("Only read " + offset + " bytes; Expected " + contentLength + " bytes");
}
try {
filename = u.getFile();
Log.i("Getting the file name ", " " + filename);
FileOutputStream out = new FileOutputStream(myDisCacheFile);
Log.i("FileDischCahce ", " " + myDisCacheFile);
out.write(data);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
return myDisCacheFile;

}

private File getImageFile(ImageSpan img) {
File newFileType = new File(context.getCacheDir().getPath(), img.getSource());
return newFileType;

}

 

private InputStream fetch(String urlString) throws MalformedURLException, IOException {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(urlString);
HttpResponse response = httpClient.execute(request);
return response.getEntity().getContent();
}

/*
* A class to handle the converstion from drawalbe to bitmap. Will adjust
* later based on the results and speed
*/

public static Bitmap drawableToBitmap(Drawable drawable) {
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
}

Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);

return bitmap;
}

/*
* This section will hanlde all the code differently --- based on some of
* abhideeps samples
*/

// ------------------------------- //

private String saveToInternalSorage(Drawable result) {
Bitmap resultB = drawableToBitmap(result);

ContextWrapper cw = new ContextWrapper(context);
// path to /data/data/yourapp/app_data/imageDir
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
// Create imageDir
File mypath = new File(directory, "profile.png");

FileOutputStream fos = null;
try {

fos = new FileOutputStream(mypath);

// Use the compress method on the BitMap object to write image to
// the OutputStream
resultB.compress(Bitmap.CompressFormat.PNG, 100, fos);

fos.close();
} catch (Exception e) {
e.printStackTrace();
}
return directory.getAbsolutePath();
}

}

01-14 11:58:16.361: E/test.getSize()(6714): 0