Answer the question
In order to leave comments, you need to log in
Why can catch get null?
I am writing an android application , I
took an example from the official website.
When trying to send a request, an exception is always thrown, but catch always gets null
Therefore, I can’t understand the reason for the exception, please help me figure out why catch gets null, and if possible, tell me why it can’t send http requests in principle.
Checking on android 4.1
try {
text2.setText(http_demo_ofcial("http://google.ru"));
}catch (Exception io){
System.out.println(io);
if(io != null) {
String str = io.getLocalizedMessage();
io.printStackTrace();
text2.setText(str);
}
}
public static String http_demo_ofcial(String args) throws Exception {
URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
return readStream(in);
} finally {
urlConnection.disconnect();
}
}
Answer the question
In order to leave comments, you need to log in
Most likely the error is that you are trying to work with the network from the UI thread. This is very similar, judging by the architecture.
I did not understand about null, in this place you should receive NetworkOnMainThreadException. In android, you cannot go to the network from the UI thread. And you can't access UI elements from non-UI threads.
Use any popular library for the network: Retrofit, okhttp, volley... To load pictures (oddly enough) other libraries are usually used: Glade, Picasso, Universal image loader...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question