Prateek Sharma
Prateek Sharma

Reputation: 678

How to send emojis (image, smileys) in a chat or message app in Android?

how to send text and emoticon/image(not the default emojis,images in asset folder) written together in a edittext to send message and chat as it is appearing in that edittext.

p.s I am sending those images in mail or message body.

I am trying a following code :

public class MainActivity extends FragmentActivity implements KeyClickListener {

private static final int NO_OF_EMOTICONS = 54;

private ListView chatList;
private View popUpView;
private ArrayList<Spanned> chats;
private ChatListAdapter mAdapter;

private LinearLayout emoticonsCover;
private PopupWindow popupWindow;

private int keyboardHeight; 
private EditText content;
CustomizeDialogWithAction customizeDialog = null; 
private LinearLayout parentLayout;

private boolean isKeyBoardVisible;
private boolean keyicon = true;


Bitmap bitmap;
Bitmap temp;
Uri URI = null;
ImageView image;

public String body;

private Bitmap[] emoticons;

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = 
                new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }

    chatList = (ListView) findViewById(R.id.chat_list);     

    parentLayout = (LinearLayout) findViewById(R.id.list_parent);

    emoticonsCover = (LinearLayout) findViewById(R.id.footer_for_emoticons);

    popUpView = getLayoutInflater().inflate(R.layout.emoticons_popup, null);

    image = (ImageView) findViewById(R.id.img);

    bitmap = EmoticonsGridAdapter.mainBitMap;

    // Setting adapter for chat list
    chats = new ArrayList<Spanned>();
    mAdapter = new ChatListAdapter(getApplicationContext(), chats);
    chatList.setAdapter(mAdapter);
    chatList.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (popupWindow.isShowing())
                popupWindow.dismiss();  
            return false;
        }
    });

    // Defining default height of keyboard which is equal to 230 dip
    final float popUpheight = getResources().getDimension(
            R.dimen.keyboard_height);
    changeKeyboardHeight((int) popUpheight);

    // Showing and Dismissing pop up on clicking emoticons button
    final ImageView emoticonsButton = (ImageView) findViewById(R.id.emoticons_button);
    emoticonsButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            if (!popupWindow.isShowing()) {

                emoticonsButton.setImageResource(R.drawable.key);

                popupWindow.setHeight((int) (keyboardHeight));

                if (isKeyBoardVisible == true) {
                    emoticonsCover.setVisibility(LinearLayout.GONE);

                } 
                else if (isKeyBoardVisible == false) {

                    emoticonsCover.setVisibility(LinearLayout.VISIBLE);

                }
                popupWindow.showAtLocation(parentLayout, Gravity.BOTTOM, 0, 0);

            } else {
                popupWindow.dismiss();
                emoticonsButton.setImageResource(R.drawable.smily_key);
            }
        }
    });
    readEmoticons();
    enablePopUpView();
    checkKeyboardHeight(parentLayout);
    enableFooterView();
}
/**
 * Reading all emoticons in local cache
 */
private void readEmoticons () {

    emoticons = new Bitmap[NO_OF_EMOTICONS];
    for (short i = 0; i < NO_OF_EMOTICONS; i++) {           
        emoticons[i] = getImage((i+1) + ".png");
    }
}
/**
 * Enabling all content in footer i.e. post window
 */
private void enableFooterView() {

    content = (EditText) findViewById(R.id.chat_content);
    content.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            if (popupWindow.isShowing()) {

                popupWindow.dismiss();

            }
        }
    });
    final Button postButton = (Button) findViewById(R.id.post_button);      

    postButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            if (content.getText().toString().length() > 0) {

                Spanned sp = content.getText();                 
                chats.add(sp);
                content.setText("");                    
                mAdapter.notifyDataSetChanged();
                //                  final Uri uri = Uri.parse(""+sp);




                customizeDialog = new CustomizeDialogWithAction(MainActivity.this);  
                customizeDialog.setTitle(""); 
                customizeDialog.cancelButton.setText("Cancel");
                customizeDialog.cancelButton.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub

                        customizeDialog.dismiss();  
                    }
                });
                customizeDialog.mailButton.setText("Mail");
                customizeDialog.mailButton.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub

                        //                          Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
                        //                          shareIntent.putExtra(Intent.EXTRA_SUBJECT, "subject");
                        //                          shareIntent.setType("message/rfc822");
                        //                          shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
                        //
                        //
                        //                          shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
                        //                          startActivity(Intent.createChooser(shareIntent, "Share via"));

                        Uri bmpUri = getLocalBitmapUri(image);
                        if (bmpUri != null) {
                            // Construct a ShareIntent with link to image
                            Intent shareIntent = new Intent();
                            shareIntent.setAction(Intent.ACTION_SEND);
                            shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
                            shareIntent.putExtra(Intent.EXTRA_TEXT, body);
                            shareIntent.setType("image/*");
                            // Launch sharing dialog for image
                            startActivity(Intent.createChooser(shareIntent, "Share Image"));    
                        } else {
                            // ...sharing failed, handle error
                        }

                        customizeDialog.dismiss();
                    }
                });
                customizeDialog.messageButton.setText("Message");
                customizeDialog.messageButton.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub

                        Uri bmpUri = getLocalBitmapUri(image);
                        if (bmpUri != null) {
                            // Construct a ShareIntent with link to image
                            Intent shareIntent = new Intent();
                            shareIntent.setAction(Intent.ACTION_SEND);
                            shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
                            shareIntent.putExtra("sms_body", body);
                            shareIntent.setType("image/*");
                            // Launch sharing dialog for image
                            startActivity(Intent.createChooser(shareIntent, "Share Image"));    
                        } else {
                            // ...sharing failed, handle error
                        }

                        customizeDialog.dismiss();
                    }
                });
                customizeDialog.show();  

            }
        }
    });
}
public Uri getLocalBitmapUri(ImageView imageView) {
    // Extract Bitmap from ImageView drawable
    Drawable drawable = imageView.getDrawable();
    Bitmap bmp = null;
    if (drawable instanceof BitmapDrawable){
        bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
    } else {
        return null;
    }
    // Store image to default external storage directory
    Uri bmpUri = null;
    try {
        File file =  new File(Environment.getExternalStoragePublicDirectory(  
                Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png");
        file.getParentFile().mkdirs();
        FileOutputStream out = new FileOutputStream(file);
        bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
        out.close();
        bmpUri = Uri.fromFile(file);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return bmpUri;
}
/**
 * Overriding onKeyDown for dismissing keyboard on key down
 */
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (popupWindow.isShowing()) {
        popupWindow.dismiss();
        return false;
    } else {
        return super.onKeyDown(keyCode, event);
    }
}
/**
 * Checking keyboard height and keyboard visibility
 */
int previousHeightDiffrence = 0;
private void checkKeyboardHeight(final View parentLayout) {

    parentLayout.getViewTreeObserver().addOnGlobalLayoutListener(
            new ViewTreeObserver.OnGlobalLayoutListener() {

                @Override
                public void onGlobalLayout() {

                    Rect r = new Rect();
                    parentLayout.getWindowVisibleDisplayFrame(r);

                    int screenHeight = parentLayout.getRootView()
                            .getHeight();
                    int heightDifference = screenHeight - (r.bottom);

                    if (previousHeightDiffrence - heightDifference > 50) {                          
                        popupWindow.dismiss();
                    }
                    previousHeightDiffrence = heightDifference;
                    if (heightDifference > 100) {

                        isKeyBoardVisible = true;
                        changeKeyboardHeight(heightDifference);

                    } else {

                        isKeyBoardVisible = false;

                    }
                }
            });
}
/**
 * change height of emoticons keyboard according to height of actual
 * keyboard
 * 
 * @param height
 *            minimum height by which we can make sure actual keyboard is
 *            open or not
 */
private void changeKeyboardHeight(int height) {

    if (height > 100) {
        keyboardHeight = height;
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LayoutParams.MATCH_PARENT, keyboardHeight);
        emoticonsCover.setLayoutParams(params);
    }
}
/**
 * Defining all components of emoticons keyboard
 */
private void enablePopUpView() {

    ViewPager pager = (ViewPager) popUpView.findViewById(R.id.emoticons_pager);
    pager.setOffscreenPageLimit(2);

    ArrayList<String> paths = new ArrayList<String>();

    for (short i = 1; i <= NO_OF_EMOTICONS; i++) {          
        paths.add(i + ".png");
    }

    EmoticonsPagerAdapter adapter = new EmoticonsPagerAdapter(MainActivity.this, paths, this);
    pager.setAdapter(adapter);

    // Creating a pop window for emoticons keyboard
    popupWindow = new PopupWindow(popUpView, LayoutParams.MATCH_PARENT,
            (int) keyboardHeight, false);

    TextView backSpace = (TextView) popUpView.findViewById(R.id.back);
    backSpace.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            KeyEvent event = new KeyEvent(0, 0, 0, KeyEvent.KEYCODE_DEL, 0, 0, 0, 0, KeyEvent.KEYCODE_ENDCALL);
            content.dispatchKeyEvent(event);    
        }
    });
    popupWindow.setOnDismissListener(new OnDismissListener() {

        @Override
        public void onDismiss() {
            emoticonsCover.setVisibility(LinearLayout.GONE);
        }
    });
}
/**
 * For loading smileys from assets
 */
private Bitmap getImage(String path) {
    AssetManager mngr = getAssets();
    InputStream in = null;
    try {
        in = mngr.open("emoticons/" + path);
    } catch (Exception e) {
        e.printStackTrace();
    }

    temp = BitmapFactory.decodeStream(in, null, null);
    return temp;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}
@Override
public void keyClickedIndex(final String index) {

    ImageGetter imageGetter = new ImageGetter() {
        public Drawable getDrawable(String source) {    
            StringTokenizer st = new StringTokenizer(index, ".");
            Drawable d = new BitmapDrawable(getResources(),emoticons[Integer.parseInt(st.nextToken()) - 1]);
            d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());

            image.setImageDrawable(d);
            return d;
        }
    };
    Spanned cs = Html.fromHtml("<img src ='"+ index +"'/>", imageGetter, null);        

    int cursorPosition = content.getSelectionStart();       
    content.getText().insert(cursorPosition, cs);

    body = content.getText().toString();

}

}

I am sending the data like this(see screenshot):my activity screenshot

but the emoticon(image) i am sending appears like this(see screenshot).![my activity second image][2]

When i send any image it will apear like this "[obj]". How to solve it please help me.

Upvotes: 3

Views: 8070

Answers (1)

Zar E Ahmer
Zar E Ahmer

Reputation: 34360

As I am creating an emoji softkeyboard for all apps like facebook,whats app , etc.

You can send emoticons easily using Unicode here . save them in a

Map<Pattern,Integer> and send them.

These unicode are already implemented on facebook,whats app and they easily behave according.

Sending Emoticons using UniCode

if you really want to send images from your assets

then try this way .

But i recommend you sending by unicodes because all apps know how to react after recieving these codes.

Upvotes: 7

Related Questions