Read ClipData To Text - Android android.content

Android examples for android.content:ClipboardManager

Description

Read ClipData To Text

Demo Code

import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.net.Uri;
import android.util.Log;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main{

    public static CharSequence coerceToText(Context context,
            ClipData.Item item) {/*from   ww w  .j  a  v  a  2s.co  m*/
        CharSequence text = item.getText();
        if (text != null) {
            return text;
        }

        Uri uri = item.getUri();
        if (uri != null) {
            FileInputStream stream = null;
            try {
                AssetFileDescriptor descr = context.getContentResolver()
                        .openTypedAssetFileDescriptor(uri, "text/*", null);
                stream = descr.createInputStream();
                InputStreamReader reader = new InputStreamReader(stream,
                        "UTF-8");

                StringBuilder builder = new StringBuilder(128);
                char[] buffer = new char[8192];
                int len;
                while ((len = reader.read(buffer)) > 0) {
                    builder.append(buffer, 0, len);
                }
                return builder.toString();

            } catch (Exception e) {
                return e.toString();
            } finally {
                if (stream != null) {
                    try {
                        stream.close();
                    } catch (IOException e) {
                    }
                }
            }

            return uri.toString();
        }

        Intent intent = item.getIntent();
        if (intent != null) {
            return intent.toUri(Intent.URI_INTENT_SCHEME);
        }

        return "";
    }

}

Related Tutorials