当前,我正在使用SdkVersion28。在运行虚拟设备并单击时。结果程序崩溃了。希望HttpUrlConnection或语法中可能存在问题。请找出我的问题。 :(
btnHit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url= new URL("https://jsonparsingdemo-
cec5b.firebaseapp.com/jsonData/moviesDemoItem.txt");
connection= (HttpURLConnection)url.openConnection();
connection.connect();
InputStream stream= connection.getInputStream();
reader= new BufferedReader(new
InputStreamReader(stream));
StringBuffer buffer= new StringBuffer();
String line;
while((line= reader.readLine()) != null){
buffer.append(line);
}
tvData.setText("buffer");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(connection != null) {
connection.disconnect();
}
try {
if(reader != null){
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
**Error is coming out--**
E/AndroidRuntime: FATAL EXCEPTION: main
android.os.NetworkOnMainThreadException
DelegatingHttpsURLConnection.connect
(DelegatingHttpsURLConnection.java:89)
HttpsURLConnectionImpl.connect(Unknown Source:0)
at com.example.akashb.jsons.Activity1$1.onClick(Activity1.java)
ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)