简体   繁体   中英

How to convert UTF-8 to String in Java

I am stuck here because after making the convertion from byte to String I works with append method but if I want to use setText instead of append, I get no text shown on my phone. And I don't want to write text next to the last one.

UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() { 
        @Override
        public void onReceivedData(byte[] arg0) {
            String data = null;
             try {
                data = new String(arg0 , "UTF-8");
                    tvAppend(mostrarEntradaAnalogica, data);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();

            }


        }
    };

public void tvAppend(TextView tv, String text) {
        final TextView ftv = tv;
        final String ftext = text;


        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ftv.append(ftext);
            }
        });


    }

use this : https://developer.android.com/reference/java/net/URLEncoder

URLEncoder.encode("臺北市", "UTF-8");

and this will encode your "string: in UTF-8 format.

Put it in a try/catch and check for IllegalArgumentException if you want to. And if you have any spaces in your string, please replace it with

string.replace(" ", "%20");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM