从URL读取文本文档的内容始终等于null

时间:2015-10-27 20:43:30

标签: java android

每当我尝试从Dropbox中获取包含版本字符串的文本文档时,它会说它等于null,即使它应该等于0.6.48。我尝试了许多不同的获取文件的方法,但它总是返回null。代码:

new Thread() {
            public void run() {
                try {
                    URL textUrl = new URL(UPDATE_API); // UPDATE_API = "https://dl.dropboxusercontent.com/s/zjlxzypgqsxvtr0/version.txt?dl=1"
                    BufferedReader bufferReader = new BufferedReader(new InputStreamReader(textUrl.openStream()));
                    String StringBuffer;
                    String stringText = "";
                    while ((StringBuffer = bufferReader.readLine()) != null) {
                        stringText += StringBuffer;
                    }
                    bufferReader.close();
                    Soundboard.REMOTE_VERSION = stringText;
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();

我错过了什么?我正在为API 23构建。我已将<uses-permission android:name="android.permission.INTERNET"/>放入我的Android清单中。

1 个答案:

答案 0 :(得分:1)

您的代码对我有用,几乎没有变化:

String UPDATE_API = "https://dl.dropboxusercontent.com/s/zjlxzypgqsxvtr0/version.txt?dl=1";
    private BufferedReader bufferReader = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


    new Thread() {
        public void run() {
            try {
                URL textUrl = new URL(UPDATE_API);
                bufferReader = new BufferedReader(new InputStreamReader(textUrl.openStream()));
                String StringBuffer = "";
                StringBuilder stringText = new StringBuilder();
                while ((StringBuffer = bufferReader.readLine()) != null) {
                    stringText.append(StringBuffer);
                }

                Log.d("--->", stringText.toString());
                Soundboard.REMOTE_VERSION = stringText;
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    bufferReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }.start();
}

尝试在try..finally中关闭BufferedReader 使用StringBuilder而不是String进行连接