簡體   English   中英

如何從外部源創建字符串資源?

[英]How to create a string resource from an external source?

我正在嘗試訪問localhost中的.php文件:

        Thread thread = new Thread(new Runnable() {

            @Override
            public void run() {
                try  {
                    System.err.println("It's working ok?");
                    String url = "http://192.168.0.112/hlsystems/api/fetch.php";
                    String charset = "UTF-8";  // Or in Java 7 and later, use the constant: java.nio.charset.StandardCharsets.UTF_8.name()
                    String param1 = "value1";
                    String param2 = "value2";
                    String query = "";

                    try {
                        query = String.format("param1=%s&param2=%s",
                                URLEncoder.encode(param1, charset),
                                URLEncoder.encode(param2, charset));
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }

                    URLConnection connection = null;
                    try {
                        connection = new URL(url + "?" + query).openConnection();
                        connection.setRequestProperty("Accept-Charset", charset);
                        InputStream response = connection.getInputStream();
                        System.err.println(response.read());
                        Toast.makeText(mainContext, response.read(),
                                Toast.LENGTH_LONG).show();
                    } catch (IOException e) {
                        e.printStackTrace();
                        Toast.makeText(mainContext, e.toString(),
                                Toast.LENGTH_LONG).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        thread.start();

運行它時,出現以下錯誤:

W/System.err: android.content.res.Resources$NotFoundException: String resource ID #0x22

如果要從外部源/ Web服務器中檢索字符串,我應該如何在XML文件中預先定義一個字符串?

完整日志:

W/System.err: 123
W/ResourceType: No package identifier when getting value for resource number 0x00000022
W/System.err: android.content.res.Resources$NotFoundException: String resource ID #0x22
W/System.err:     at android.content.res.Resources.getText(Resources.java:250)
W/System.err:     at android.widget.Toast.makeText(Toast.java:268)
W/System.err:     at com.hlsystems.ericsonwillians.saltodepirapora.MainActivity$2.run(MainActivity.java:89)
W/System.err:     at java.lang.Thread.run(Thread.java:841)

response.read()返回一個int,即響應的單個字節。

敬酒之前,您需要將流響應轉換為完整的String。

makeText方法被重載以接受R.string資源ID作為第二個參數,它們是只讀資產,並且您不能在運行時創建

如果您只關心那個字節,請參閱

在吐司上顯示整數

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM