机器人,UTF8 - 如何确保UTF8用于共享preference [英] android, UTF8 - How do I ensure UTF8 is used for a shared preference

查看:167
本文介绍了机器人,UTF8 - 如何确保UTF8用于共享preference的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何确保UTF8用于共享preference菜单?我有一个Android preferences菜单,允许用户设置自己的名字,除其他事项。

How do I ensure UTF8 is used for a shared preference menu? I have an android preferences menu that allows a user to set their name, amongst other things.

我需要知道如何存储在共享preferences将数据转换为UTF-8格式

I need to know how to convert the data stored in shared preferences into UTF8 format

在preference菜单的布局在XML中使用utf8编码的文件在res / XML文件夹,名为设置,如下所示:

The preference menu is laid out in xml using utf8 encoding in a file called settings in the res/xml folder and looks like this:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
    xmlns:android="http://schemas.android.com/apk/res/android">
    <EditTextPreference
        android:key="@string/name_key"
        android:title="@string/hof_name_title"
        android:summary="@string/hof_name_summary"
        android:defaultValue="Anonymous" />
    <CheckBoxPreference
        android:key="@string/new_game_preference_key"
        android:title="@string/new_game_preference_title"
        android:summary="@string/new_game_preference_summary"
        android:defaultValue="false" />
</PreferenceScreen>

这是处理这一类是

public class PrefsActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.settings);
    }

    @Override
    protected void onPause() {
        super.onPause();
        // Unregister the listener whenever a key changes
        getPreferenceScreen().getSharedPreferences()
                .unregisterOnSharedPreferenceChangeListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        // Set up a listener whenever a key changes
        getPreferenceScreen().getSharedPreferences()
                .registerOnSharedPreferenceChangeListener(this);
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
            String key) {
//      Util.log_debug_message("@@@@ Changed prefrence key = " + key);
        if (key.equalsIgnoreCase(getString(R.string.name_key))){
            update_webserver();
        }else if (key.equalsIgnoreCase(getString(R.string.new_game_preference_key))){
            update_webserver();
        }
    }

    protected void update_webserver(){
        Intent webServerReg = new Intent(this, RegService.class);
        webServerReg.putExtra(Config.C2DM_REG_ID_EXTRA, C2DMessaging.getRegistrationId(this));
        startService(webServerReg);     
    }
}

我认为设置&LT; XML版本=1.0编码=UTF-8&GT; 将确保文本将是连接codeD UTF8格式,但情况并非总是如此。我在各种格式获得价值。一些例子

I assumed that setting <?xml version="1.0" encoding="utf-8"?> would ensure that text would be encoded in UTF8 format but this is not always the case. I am getting values in all sorts of formats. Some examples

\ NFE \ xF1a,L \ xFAcia,$'\ xE5 \ XEE',

"\nFe\xF1a", "L\xFAcia", "$'\xE5 \xEE'",

":-$B-)O:-):-P=-OB-):-D:-Q:-X:-!:-|\n:'(:-*XDo_O:-X:-C:-X:O:-X=-O;-):-):-);-):-D:OX-(o_O:-V:-@:-V:-X:-Do_O::-C   \xBF\xA1\xA1\xAB\xBB\xAE\xA9^\xA5\xA5?[\xA2}?\xA2\xA2\xA5\xA3?$\xBF\xA1\xAE\xA7><[\xA3~?=~~<$c$c>\xB0]\xA3?\xA7\xA1\\\xAB\xBB\xAE^``]]||||}{_|]|||\xB0\xB0?"

":-$B-)O:-):-P=-OB-):-D:-Q:-X:-!:-|\n:'(:-*XDo_O:-X:-C:-X:O:-X=-O;-):-):-);-):-D:OX-(o_O:-V:-@:-V:-X:-Do_O::-C \xBF\xA1\xA1\xAB\xBB\xAE\xA9^\xA5\xA5?[\xA2}?\xA2\xA2\xA5\xA3?$\xBF\xA1\xAE\xA7><[\xA3~?=~~\xB0]\xA3?\xA7\xA1\\\xAB\xBB\xAE^``]]||||}{_|]|||\xB0\xB0?"

是的,这是loooong一套rubish在最后一个例子。

Yes that is one loooong set of rubish in the last example.

我有问题,尝试使用以下code发送NMES作为JSON HTTP POST或PUT请求到我的网络服务器时,启动

The problems I have start when trying to send the nmes as a json HTTP POST or PUT request to my webserver using the following code

public void update(String regId) throws AuthenticationException {
    JSONObject mu_to_send = createJsonToPost(regId, false);
    HttpResponse response;
    try {
        response = HttpRequest.httpPutJSONObject(this,
                Config.UPDATE_USER_URL, mu_to_send);
        int responseCode = response.getStatusLine().getStatusCode();
        String responseJson;
        try {
            responseJson = EntityUtils.toString(response.getEntity());
            String msg = "";

            if (responseCode == 201) {
                // mobile_user = new
                // JSONObject(responseJson).getJSONObject("mobile_user");
                // Broadcast.sendBroadcast(this,
                // ResponseReceiver.ACTION_RESP,
                // Intent.CATEGORY_DEFAULT, Config.C2DM_MESSAGE_EXTRA,
                // Config.BROADCAST_WEBSERVER_USER_CREATED);
            } else {
                msg = "Failed to register with server! HTTP response code = "
                        + responseCode;
            }
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } catch (ClientProtocolException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

}

public JSONObject createJsonToPost(String regId, boolean set_password) {
    JSONObject holder = new JSONObject();
    JSONObject data = new JSONObject();
    try {
        data.put("auth", regId);
        data.put("name", C2DMessaging.getName(this));
        data.put("receive_new_game_notification",
                C2DMessaging.getGameStartedNotificationPreference(this));
        holder.put("mobile_user", data);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return holder;
}

public static HttpResponse httpPutJSONObject(Context context, String url,
        JSONObject data) throws ClientProtocolException, IOException,
        AuthenticationException {
    DefaultHttpClient httpclient = getHttpClient(context);
    HttpPut httpput = new HttpPut(url);
    httpput.addHeader("User-Agent", Config.USER_AGENT);
    httpput.addHeader("Accept", "application/json");
    httpput.addHeader("Content-type", "application/json");
    httpput.addHeader(new BasicScheme().authenticate(
            getCredentials(context), httpput));
    StringEntity se = new StringEntity(data.toString());

    httpput.setEntity(se);
    return httpclient.execute(httpput);
}

这会导致各种问题而预计有效的JSON(即UTF8)我的Web服务器上 作为JSON应该首先被送到EN codeD的UTF8。

This causes all sorts of issues on my web server which expects valid JSON (i.e. UTF8) as JSON should be sent encoded in UTF8 in the first place.

于是

1)为什么不&LT; XML版本=1.0编码=UTF-8&GT; 实际设置UTF8编码?在布局中使用时?

1) Why doesn't <?xml version="1.0" encoding="utf-8"?> actually set UTF8 encoding? when used in the layout?

2)如何最好地确保我总是发送到我的Web服务器有效UTF8格式的字符? 如果这种由PUT请求,或由code,它保存到共享preference或或由code表示填充JSON对象或者以上的组合处理 ?还是其他什么东西?

2) How best to ensure that I always get valid UTF8 format characters sent to my web server? Should this be handled by the put request or by the code that saves to the shared preference or or by the code that populates the json object or perhaps a combination of the above ? or something else?

这是从这个回报率问题上遵循<一href="http://stackoverflow.com/questions/9167468/rails-3-how-to-handle-pg-error-incomplete-multibyte-character">Rails 3 - 如何处理PG错误不完整的多字节字符

This is a follow on from this RoR question Rails 3 - How to handle PG Error incomplete multibyte character

推荐答案

关键是要了解的 UTF-8 统一code

  • 在Java中使用统一code处理内存中的字符和字符串。每个字符存储在两个字节。
  • 当文本​​进程之间传输(例如到Web服务器)的的它被写入/从磁盘中读取,在内部重新presentation转换成过度的有线格式。这是在编码或解码。 UTF-8是最流行的,但其他格式包括:
    • UTF-16
    • ISO 8859-1
    • Java processes characters and strings in memory using Unicode. Each character is stored in two bytes.
    • When text is transmitted between processes (eg to a web server) or it is written to/read from disk, the internal representation is converted into an over-the-wire format. This is the encoding or decoding. UTF-8 is the most popular, but other formats include:
      • UTF-16
      • ISO 8859-1

      在你的问题,你提到的XML文件是EN codeD的UTF-8:那好,你就能够把外国字符的文件,但指定编码的只对于特定的XML文件的。

      In your question, you mention that the XML files are encoded in utf-8: That is good, and you will be able to put foreign characters in the files, but that specifies the encoding only for that specific XML file.

      这些XML文件将被编译成Android的资源,将包含正确的值(你可以检查它,如果你喜欢在调试器,或者通过$ P $从构建链pserving中间Java资源文件)。

      These XML files will be compiled into Android resources and will contain the correct values (you can check it if you like in the debugger, or by preserving the intermediate Java resource files from the build chain).

      现在的问题是几乎可以肯定,你发送的数据和从HTTP服务器接收数据,具体在哪里,该数据字节之间的网络和Java的转换字符串 。目前不设置它的要求 - 这可以如文档中描述的阿帕奇了HTTPClient

      The problem is almost certainly where you send data to and receive data from the HTTP server, specifically where that data is converted between the bytes on the network and a Java String. Currently you are not setting it in the request - this can be done as described in the documentation for Apache HTTPClient.

      尽管服务器可能已经需要/想这,这当然是一件好事,明确规定在请求。

      Although the server might already require/assume this, it's certainly a good thing to state clearly in the request.

      您还需要确保服务器(一个在<一个href="http://stackoverflow.com/questions/9167468/rails-3-how-to-handle-pg-error-incomplete-multibyte-character">Rails 3 - 如何处理PG错误不完整的多字节字符):

      You also need to ensure that the server (the one in Rails 3 - How to handle PG Error incomplete multibyte character):

      • 在期待UTF-8
      • 在德codeS使用UTF-8日codeR请求
      • 恩codeS使用UTF-8编码的响应

      (很抱歉,但我不知道Ruby on Rails的,所以我不知道如何具体帮助那里)。

      (Sorry, but I don't know Ruby on Rails so I don't know how to specifically help there).

      早在Android的最后,你还需要确保你的HTTP库是用UTF-8日codeR响应解码。如果您处理此自己,请确保您使用String构造是这样的一个,参数是UTF-8:

      Back in the Android end, you also need to ensure that your HTTP library is decoding the response with the UTF-8 decoder. If you handle this yourself, ensure that the String constructor you use is this one, and the argument is "utf-8":

      • <一个href="http://developer.android.com/reference/java/lang/String.html#String%28byte%5b%5d,+java.lang.String%29"相对=nofollow>公共字符串(byte []的数据,字符串的charsetName)

      在客户端和服务器使用UTF-8,您的问题将会得到解决。

      Once BOTH the client and the server are using UTF-8, your problems will be resolved.

      为了帮助调试在这里,我建议:

      To help debugging here, I suggest:

      1. 在一些服务器上的日志报表的的客户端打印尽可能接近到HTTP code相关的字符串
      2. 通过配置交谈通过调试代理的客户端运行。检查请求和响应,并检查他们确实是UTF-8。代理包括:

      1. A number of logging statements on server and client that print the relevant strings as close as possible to the HTTP code
      2. Running with the client configured to talk through a debugging proxy. Examine the request and response and check that they are indeed UTF-8. Proxies include:

      • Charles
      • WebScarab
      • Fiddler

      这篇关于机器人,UTF8 - 如何确保UTF8用于共享preference的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆