【问题标题】:I don't understand these codes我不明白这些代码
【发布时间】:2018-03-01 21:11:57
【问题描述】:

我正在为我在学校的期末项目制作一个 Android 应用程序。 我只知道基本的 Java,我需要让我的应用程序连接到我的 mysql 数据库。

所以我在这里使用 get 方法按照本教程进行操作:

https://www.tutorialspoint.com/android/android_php_mysql.htm

除了php部分以及它如何连接和执行代码之外,我不明白的是这一行

StringBuffer sb = new StringBuffer("");
String line="";

while ((line = in.readLine()) != null) {
    sb.append(line);
    break;
}

in.close();
return sb.toString();

我试着读这个:

https://developer.android.com/reference/java/lang/StringBuffer.html

但是我的英语很烂,阅读这不会让我理解 StringBuffer 做了什么。我只知道它返回了一些东西并且它被转换为字符串类型所以我认为它是php结果。

我想知道的是上面教程中的StringBuffer是做什么的?他们是否返回 php 结果的值?

如果他们这样做,我可以这样使用它吗?因为我试图这样做,但遇到了一个问题(异常 e),e.getMessage is null

TextView text2 = (TextView) findViewById(R.id.textView);
text2.setText(sb.toString());

如果没有,我如何将 php 值的结果设置为我的 textview?

【问题讨论】:

  • 由于您是从输入流中一次读取每一行并将其添加到String,因此使用StringBuffer 会更快。

标签: android stringbuffer


【解决方案1】:

StringBuffer 是一种逐段构建字符串的方法。它是手动连接字符串的替代方法:

String string3 = string0 + string1 + string2;

你会这样做。

stringBuffer.append(string0)
    .append(string1)
    .append(string2);

因此,它所做的只是逐行从 in 中获取字符串并将其组合成一个字符串。

【讨论】:

    【解决方案2】:

    好吧,伙计,这取决于您期望连接到数据库的结果,例如发送或获取一些数据,然后您还需要一个 php 文件。 但是连接 db 最简单的方法是使用VolleyAsyncTask。 分析这些示例代码,它可以正常工作(但您需要一个与您的请求连接的 php 文件:

    private class YourTask extends AsyncTask<Void, Void, String> {
    
        @Override
        protected String doInBackground(Void... voids) {
            String strUrl = "http://YOUR_PLACE_ON_A_SERVER_WHERE_THE_PHP_FILE_IS.php";
            URL url = null;
            StringBuffer sb = new StringBuffer();
    
            try {
                url = new URL(strUrl);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.connect();
                InputStream iStream = connection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(iStream));
                String line = "";
    
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
    
                reader.close();
                iStream.close();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            return sb.toString();
        }
    //Here you can manage things you want to execute
    }
    

    【讨论】:

      猜你喜欢
      • 2012-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-12
      • 2021-03-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多