当尝试从网站获取数据时,我有致命异常; 我的代码在这里,
这是我的代码Java类:
public class TestInternetClass extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... strings) {
try {
URL url=new URL(strings[0]);
HttpURLConnection connection= (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.connect();
InputStream stream=connection.getInputStream();
InputStreamReader reader=new InputStreamReader(stream);
StringBuilder builder=new StringBuilder();
int temp=reader.read();
while (temp!=-1){
builder.append((char)temp);
temp=reader.read();
}
reader.close();
stream.close();
connection.disconnect();
return builder.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
Log.i("InternetData",s);
super.onPostExecute(s);
}
}
和主要内容:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TestInternetClass testInternetClass=new TestInternetClass();
testInternetClass.execute("https://www.gsm.ir/");
}
}
我的清单:
android:name="android.permission.INTERNET"/>
android:name="android.permission.ACCESS_NETWORK_STATE"/>
这是我的错误:
11-07 23:46:07.318 9703-9703/com.fr6ad.testweathwe E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.fr6ad.testweathwe, PID: 9703
java.lang.NullPointerException: println needs a message
at android.util.Log.println_native(Native Method)
at android.util.Log.i(Log.java:211)
at com.fr6ad.testweathwe.TestInternetClass.onPostExecute(TestInternetClass.java:53)
at com.fr6ad.testweathwe.TestInternetClass.onPostExecute(TestInternetClass.java:19)
at android.os.AsyncTask.finish(AsyncTask.java:660)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:677)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6682)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
答案 0 :(得分:0)
您正在从null
函数返回doInBackground()
,并且您的onPostExecute(String s)
的{{1}}调用不希望使用null参数。就像其他人说的那样,添加空检查将纠正当前的问题,但是它掩盖了更大的潜在问题。那个问题是,您抛出了MalformedURLException或IOException。
直接的解决方法是简单地添加一个空检查
Log.i
但是,我强烈建议您找出代码中发生的其他情况以及与您抛出的MalformedURLException或IOException有关的真正错误。