Continuing from my previous post, I was able to set multiple elements to the MultiAutoCompleteTextView but I was not able to wrap those items with custom background and close button as in that link picture.
I was able to do the same with single element but for multiple, ran out of luck.
This is what I tried.
// set text to MultiAutoCompleteTextView
private void setTextSample(String contactName) {
final SpannableStringBuilder sb = new SpannableStringBuilder();
TextView tv = (TextView) LayoutInflater.from(this).inflate(R.layout.textview, null);
tv.setText(contactName);
BitmapDrawable bd = (BitmapDrawable) convertViewToDrawable(tv);
bd.setBounds(0, 0, bd.getIntrinsicWidth(), bd.getIntrinsicHeight());
sb.append(contactName + ",");
sb.setSpan(new ImageSpan(bd), sb.length()-(contactName.length()+1),
sb.length()-1,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
mMultiAutoCompleteTextView.setText(sb);
}
// wrap text with custom elements
private static Object convertViewToDrawable(View view) {
int spec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
view.measure(spec, spec);
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
Bitmap b = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(),
Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
c.translate(-view.getScrollX(), -view.getScrollY());
view.draw(c);
view.setDrawingCacheEnabled(true);
Bitmap cacheBmp = view.getDrawingCache();
Bitmap viewBmp = cacheBmp.copy(Bitmap.Config.ARGB_8888, true);
view.destroyDrawingCache();
return new BitmapDrawable(viewBmp);
}
Any help is greatly appreciated.
Edit :
If I do
mMultiAutoCompleteTextView.setText(mMultiAutoCompleteTextView.getText().toString()+", "+sb);
I am getting multiple texts but they are not wrapped with custom background.
Not getting where I am going wrong.
Edit :
Sample multiple elements would look something like this
try this:
class MyMultiAutoCompleteTextView extends MultiAutoCompleteTextView {
public MyMultiAutoCompleteTextView(Context context) {
super(context);
}
#Override
protected void replaceText(CharSequence text) {
Log.d(TAG, "replaceText " + text.getClass() + " " + text);
super.replaceText(getSpanned(text.toString()));
}
}
private Spanned getSpanned(String name) {
TextView tv = (TextView) LayoutInflater.from(this).inflate(R.layout.test, null);
tv.setText(name);
SpannableStringBuilder sb = new SpannableStringBuilder(name);
sb.setSpan(new ViewReplacementSpan(tv), 0, sb.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return sb;
}
class ViewReplacementSpan extends DynamicDrawableSpan {
private View v;
private Drawable drawable;
public ViewReplacementSpan(View v) {
super(ALIGN_BOTTOM);
this.v = v;
int spec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
v.measure(spec, spec);
v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
drawable = new SpanDrawable();
drawable.setBounds(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
}
#Override
public Drawable getDrawable() {
return drawable;
}
class SpanDrawable extends Drawable {
#Override
public void draw(Canvas canvas) {
canvas.clipRect(getBounds());
v.draw(canvas);
}
#Override
public void setAlpha(int alpha) {
}
#Override
public void setColorFilter(ColorFilter cf) {
}
#Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
}
}
test it with the following in onCreate():
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
MultiAutoCompleteTextView mactv = new MyMultiAutoCompleteTextView(this);
ArrayAdapter<Spanned> a = new ArrayAdapter<Spanned>(this, android.R.layout.simple_dropdown_item_1line);
String[] names = { "Jane", "John", "Mary", "Mark" };
for (String name: names) {
a.add(getSpanned(name));
}
Tokenizer tokenizer = new MultiAutoCompleteTextView.CommaTokenizer();
mactv.setTokenizer(tokenizer);
mactv.setAdapter(a);
mactv.setThreshold(1);
SpannableStringBuilder sb = new SpannableStringBuilder();
for (int i = 0; i < 2; i++) {
sb.append(tokenizer.terminateToken(a.getItem(i)));
}
mactv.setText(sb);
ll.addView(mactv);
TextView tv = new TextView(this);
tv.setGravity(Gravity.CENTER);
tv.setText("try: Jane, John, Mary or Mark");
tv.setTextSize(32);
ll.addView(tv);
setContentView(ll);
I think you have problem here:
mMultiAutoCompleteTextView.setText(mMultiAutoCompleteTextView.getText().toString()+", "+sb);
When you call mMultiAutoCompleteTextView.getText().toString(), you convert your spannableString to ordinary string, which can't hold background or smth else.
Try to save your current SpannableStringBuilder somewhere and work like that:
mBuilder.append(sb);
mMultiAutoCompleteTextView.setText(mBuilder);
Related
I created a custom edit text view for add tags its working fine for me but some vivo devices its not working.
Scenario is that when I type a char like as char A then characters sequence will be 'A' after that I type B then characters sequence will be 'AB' and then I type C char sequence should be 'ABC' but its not accepting char C and remove 'B' as well.
public class TagEditText extends android.support.v7.widget.AppCompatEditText {
TextWatcher textWatcher;
String lastString;
String separator = " ";
CharSequence sts = "";
public TagEditText(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
setMovementMethod(LinkMovementMethod.getInstance());
textWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Log.i("CharSequence1", s.toString());
sts = s;
}
#Override
public void afterTextChanged(Editable s) {
Log.i("CharSequence2", s.toString());
String thisString = s.toString();
if (thisString.length() > 0 && !thisString.equals(lastString)) {
format();
}
}
};
addTextChangedListener(textWatcher);
}
private void format() {
SpannableStringBuilder sb = new SpannableStringBuilder();
String fullString = getText().toString();
String[] strings = fullString.split(separator);
for (int i = 0; i < strings.length; i++) {
String string = strings[i];
sb.append(string);
if (fullString.charAt(fullString.length() - 1) != separator.charAt(0) && i == strings.length - 1) {
break;
}
BitmapDrawable bd = (BitmapDrawable) convertViewToDrawable(createTokenView(string));
bd.setBounds(0, 0, bd.getIntrinsicWidth(), bd.getIntrinsicHeight());
int startIdx = sb.length() - (string.length());
int endIdx = sb.length();
sb.setSpan(new ImageSpan(bd), startIdx, endIdx, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
MyClickableSpan myClickableSpan = new MyClickableSpan(startIdx, endIdx);
sb.setSpan(myClickableSpan, Math.max(endIdx - 2, startIdx), endIdx, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
if (i < strings.length - 1) {
sb.append(separator);
} else if (fullString.charAt(fullString.length() - 1) == separator.charAt(0)) {
sb.append(separator);
}
}
lastString = sb.toString();
setText(sb);
setSelection(sb.length());
}
public View createTokenView(String text) {
LinearLayout l = new LinearLayout(getContext());
l.setOrientation(LinearLayout.HORIZONTAL);
l.setGravity(Gravity.CENTER_VERTICAL);
l.setBackgroundResource(R.drawable.bordered_rectangle_rounded_corners);
TextView tv = new TextView(getContext());
l.addView(tv);
tv.setText(text);
tv.setPadding(0, 0, 5, 0);
tv.setTextColor(ContextCompat.getColor(getContext(), R.color.chocolateTextColor));
tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
ImageView im = new ImageView(getContext());
l.addView(im);
im.setImageResource(R.drawable.delete_tag);
im.setScaleType(ImageView.ScaleType.FIT_CENTER);
return l;
}
public Object convertViewToDrawable(View view) {
int spec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
view.measure(spec, spec);
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
Bitmap b = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
c.translate(-view.getScrollX(), -view.getScrollY());
view.draw(c);
view.setDrawingCacheEnabled(true);
Bitmap cacheBmp = view.getDrawingCache();
Bitmap viewBmp = cacheBmp.copy(Bitmap.Config.ARGB_8888, true);
view.destroyDrawingCache();
return new BitmapDrawable(getContext().getResources(), viewBmp);
}
private class MyClickableSpan extends ClickableSpan {
int startIdx;
int endIdx;
public MyClickableSpan(int startIdx, int endIdx) {
super();
this.startIdx = startIdx;
this.endIdx = endIdx;
}
#Override
public void onClick(View widget) {
String s = getText().toString();
String s1 = s.substring(0, startIdx);
String s2 = s.substring(Math.min(endIdx + 1, s.length() - 1), s.length());
TagEditText.this.setText(s1 + s2);
}
}
}
XML code
<com.thevipgroup.views.TagEditText
android:id="#+id/tags"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="#dimen/dp_30"
android:layout_marginStart="#dimen/dp_30"
android:layout_marginTop="#dimen/dp_20"
android:background="#drawable/white_round_semi_transparent"
android:cursorVisible="true"
android:focusable="true"
android:focusableInTouchMode="true"
android:gravity="center_vertical"
android:hint="#string/tags_hint"
android:maxHeight="#dimen/dp_150"
android:minHeight="#dimen/dp_45"
android:paddingLeft="#dimen/dp_16"
android:paddingRight="#dimen/dp_16"
android:singleLine="true"
android:textColor="#color/chocolateTextColor"
android:textColorHint="#color/textHintColorGrey"
android:textSize="#dimen/sp_15"
fontpath:customFont="fonts/SF-UI-DISPLAY-REGULAR.TTF" />
I have to show text and images exactly as TextView holds. spannable object can be used but the problem is images are being downloaded from server at run time and have to display placeholder till images are downloaded..
So I am thinking of creating Custom TextView which extends a ViewGroup but then there would be a lot of handling. let me know if there is another best option available because I have shortage of time
This can be achieved by using SpannableString and ImageSpan classes. An instance of SpannableString can be created and can be set to TeaxtView.
Instance of SpannableString can contain combination of Text and Image. Here is a quick example I could find:
public class TestActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView textView = (TextView) findViewById(R.id.textview);
SpannableString ss = new SpannableString("abc");
Drawable d = getResources().getDrawable(R.drawable.icon32);
d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
ss.setSpan(span, 0, 3, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
textView.setText(ss);
}
Have a look at this link as well
I think the easiest way to achieve this is to create a custom TextView that inside uses Html.fromHtml() to add the images and the text. You can then feed it the placeholder and when the images load you simply update with the new image. You wouldn't need to handle almost anything.
The stuff you pass to the TextView could be something of the sort:
CustomTextView(String text, List<...> plceholders)
With the text containing string placeholders for where the images should be fitted, something like "{img} test message {img}" and then a simple search and replace for {img} with the <img> tag should be enough.
You can find plenty of samples online about Html.fromHtml().
Also, N-JOY's Spannable String solution would work.
Here is the solution I implemented.
Spanned spanned = null;
String messageCustomized = "<img src ='"+ WebConstant.IMAGE_BASE_URL +
part +"'/>";//WebConstant.IMAGE_BASE_URL + part;
Spanned span = Html.fromHtml(messageCustomized, new
URLImageParser(sentMessagesViewHolder.tvMessage, context), null);
if (spanned!=null) {
spanned = (Spanned) TextUtils.concat(spanned, span);
}else spanned= span;
if (spanned!=null) {
txtView.setText(spanned);
}
Image Getter
public class URLImageParser implements ImageGetter {
Context context;
View container;
private int imageSize = 20;
private int imageSizeDisplaySize = 20;
URLDrawable urlDrawable = null;
public URLImageParser(View container, Context context) {
this.context = context;
this.container = container;
imageSize = Utility.convertDpTopPixels(context, 20);
imageSizeDisplaySize = Utility.convertDpTopPixels(context, 35);
}
#Override
public Drawable getDrawable(final String url) {
String[] arr = url.split("/");
final String fileName = arr[arr.length - 1];
urlDrawable = new URLDrawable();
Drawable drawable = null;
if (Build.VERSION.SDK_INT >= 21)
drawable =
context.getDrawable(R.drawable.profile_main_placeholder);
else
drawable = context.getResources().getDrawable(R.drawable.profile_main_placeholder);
drawable.setBounds(0, 0, 0 + imageSize, 0 + imageSize);
urlDrawable.drawable = drawable;
Bitmap bitmap = null;
bitmap = ImageUtility.getImageFromSDCard(fileName);
if (bitmap != null) { // the bitmap is available
bitmap = RoundedImageView.getCroppedBitmap(bitmap, imageSize, imageSize, imageSize);
drawable = new BitmapDrawable(context.getResources(), bitmap);//ImageUtility.bitmapToDrawable(context,resource);
drawable.setBounds(0, 0, 0 + imageSize, 0 + imageSize); //set the correct bound according to the result from HTTP call
URLImageParser.this.urlDrawable.drawable = drawable;
} else
Glide.with(context)
.load(url)
.asBitmap()
.transform(new CircleTransform(context))
.override(imageSizeDisplaySize, imageSizeDisplaySize)
.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
// you can do something with loaded bitmap here
// .....
Drawable drawable = new BitmapDrawable(context.getResources(), resource);//ImageUtility.bitmapToDrawable(context,resource);
drawable.setBounds(0, 0, 0 + imageSize, 0 + imageSize); //set the correct bound according to the result from HTTP call
URLImageParser.this.urlDrawable.drawable = drawable;
URLImageParser.this.container.invalidate();
ImageUtility.saveImageToSDCard(resource, fileName);
}
});
return urlDrawable.drawable; //return reference to URLDrawable where We will change with actual image from the src tag
//}
}
}
Custom Bitmap Drawable
public class URLDrawable extends BitmapDrawable {
// the drawable that you need to set, you could set the initial drawing
// with the loading image if you need to
protected Drawable drawable;
#Override
public void draw(Canvas canvas) {
// override the draw to facilitate refresh function later
if(drawable != null) {
drawable.draw(canvas);
}
}
}
i've been searching but got no results on adding custom images as emoji in android application.Thank you for any kind of help
Here is my problem :
I've trying to do a custom keyboard in android which includes only custom images as emoji,i manage to show image in keyboard but when i try to send it ,i get [OBJ] in return.
Here is some of my code , i tried many possible ways ;
String s = "<img src='a.png'/>";
// Spanned cs = Html.fromHtml("<img src='" + getResources().getDrawable(R.drawable.a) + "'/>", imageGetter, null);
/* ic.commitText( Html.fromHtml(s, new Html.ImageGetter() {
#Override public Drawable getDrawable(String source) {
Drawable drawFromPath;
int path =
emoji.this.getResources().getIdentifier(source, "drawable",
"com.cmosteknoloji.emoji");
drawFromPath = (Drawable) emoji.this.getResources().getDrawable(path);
drawFromPath.setBounds(0, 0, drawFromPath.getIntrinsicWidth(),
drawFromPath.getIntrinsicHeight());
return drawFromPath;
}
}, null),1);*/
Spanned spanned = Html.fromHtml(s, this, null);
ic.commitText(spanned,1);
#Override
public Drawable getDrawable(String arg0) {
// TODO Auto-generated method stub
int id = 0;
if(arg0.equals("a.png")){
id = R.drawable.a;
}
LevelListDrawable d = new LevelListDrawable();
Drawable empty = getResources().getDrawable(id);
d.addLevel(0, 0, empty);
d.setBounds(0, 0, empty.getIntrinsicWidth(), empty.getIntrinsicHeight());
return d;
}
ImageGetter imageGetter = new ImageGetter() {
#Override
public Drawable getDrawable(String source) {
byte [] encodeByte=Base64.decode("iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==",Base64.DEFAULT);
Bitmap bitmap=BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
Drawable d = new BitmapDrawable(bitmap);
Log.e("Chk", "Height : "+d.getIntrinsicHeight());
Log.e("Chk", "Width : " + d.getIntrinsicWidth());
return d;
}
};
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);
I have code to create view programmatically like this ,
splash.post(new Runnable() {
#Override
public void run() {
processFromDatabase();
}
});
splash is my parent view , and this is processFromDatabase Code
private void processFromDatabase() {
createLayoutBook("food_name", "80000", "food_des","", 2);
Bitmap bmp = merge();
saveToLocal2(bmp);
}
and this is my code for createLayoutBook ,
private void createLayoutBook(String food_name, String food_price,String food_des, String path, int tag) {
Log.e("create layout book", "Create layout book");
RelativeLayout root_2book = new RelativeLayout(c);
RelativeLayout.LayoutParams rlp_a = new RelativeLayout.LayoutParams(
LayoutParams.FILL_PARENT, ((int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, 120, c.getResources()
.getDisplayMetrics())));
rlp_a.setMargins(0, 10, 0, 0);
root_2book.setLayoutParams(rlp_a);
root_2book.setBackgroundColor(c.getResources().getColor(R.color.krem));
RelativeLayout layout_detail_2book = new RelativeLayout(c);
RelativeLayout.LayoutParams rdet = new RelativeLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
rdet.addRule(RelativeLayout.RIGHT_OF, layout_a_2book.getId());
rdet.setMargins(20, 3, 0, 0);
layout_detail_2book.setLayoutParams(rdet);
TextView tv_nama_2book = new TextView(c);// nama
tv_nama_2book.setId(id_book);
id_book = id_book + 1;
RelativeLayout.LayoutParams tv_nama = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
tv_nama_2book.setLayoutParams(tv_nama);
tv_nama_2book.setTextSize(20);
tv_nama_2book.setTypeface(Typeface.DEFAULT_BOLD);
tv_nama_2book.setText(food_name);
Log.e("food name", food_name);
getSharedPreferences("myprefs", 0).edit().putString("food_name", food_name).commit();
TextView tv_des_2book = new TextView(c); // des
RelativeLayout.LayoutParams tv_des = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
tv_des.addRule(RelativeLayout.BELOW, tv_nama_2book.getId());
tv_des.setMargins(0, 3, 5, 0);
tv_des_2book.setLayoutParams(tv_des);
tv_des_2book.setTextSize(12);
tv_des_2book.setTextColor(c.getResources().getColor(R.color.hitam));
tv_des_2book.setText(food_des);
Log.e("food des", food_des);
getSharedPreferences("myprefs", 0).edit().putString("food_des", food_des).commit();
layout_detail_2book.addView(tv_nama_2book);
layout_detail_2book.addView(tv_des_2book);
root_2book.addView(layout_detail_2book);
splash.addView(root_2book);
and this is code for change this layout to bitmap
public Bitmap merge() {
View v1 = splash;
v1.setDrawingCacheEnabled(true);
Bitmap merge = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
return merge;
}
But why , it return with black screen , like my layout that I created before not save or missing , any solution?? thanks
I believe what you want something like this:
public Bitmap merge() {
Bitmap bitmap = Bitmap.createBitmap(...);
Canvas canvas = new Canvas(bitmap);
splash.draw(canvas);
return bitmap;
}