我在這裏問的所有其他解決方案沒有奏效。我想從網上讀取文本文件,並將此字符串放入文本視圖中。我現在只是在測試,文本文件中唯一的值是「223」。我的應用開始崩潰任何人都可以請幫忙?從URL讀取文本文件並輸出到TextView
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.StringBuilderPrinter;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
private TextView textView;
private StringBuilder text = new StringBuilder();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BufferedReader reader = null;
try {
URL url = new URL("http://something.uk/pmt/status.txt");
reader = new BufferedReader(
new InputStreamReader(url.openStream()));
String str;
while ((str = reader.readLine()) != null) {
text.append(str);
text.append('\n');
}
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Error reading file.", Toast.LENGTH_LONG).show();
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (MalformedURLException e) {
}
catch (IOException e) {
}
}
TextView output = (TextView) findViewById(R.id.textView);
output.setText((CharSequence) text);
}
}
}
堆棧跟蹤:
請從logcat發佈您的錯誤 –
如何使用logcat?我在終端上試過adb logcat,但沒有奏效。 – JB2000
錯誤很明顯...... NetworkOnMainThread ....這意味着你必須從另一個線程的try catch執行代碼。 –