我不太清楚为什么我会得到一个NullPointerException,这是Java的新手,所以任何帮助都会非常感谢!
public class MainActivity extends AppCompatActivity {
private TextView httpstuff;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView httpstuff = (TextView)findViewById(R.id.tvHttp);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(
new Button.OnClickListener(){
public void onClick(View v){
new JSONTask().onPostExecute("http://samples.openweathermap.org/data/2.5/weather?q=Chicago&appid=93eea9a9277a0520d2f444c3ff8c62da");
}
}
);
}
class JSONTask extends AsyncTask<String,String,String> {
@Override
protected String doInBackground(String... urls) {
HttpsURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL("https://samples.openweathermap.org/data/2.5/weather?q=Chicago&appid=93eea9a9277a0520d2f444c3ff8c62da");
connection = (HttpsURLConnection) 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);
}
return buffer.toString();
} 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();
}
}
return null;
}
@Override
protected void onPostExecute (String result){
super.onPostExecute(result);
httpstuff.setText(result);
}
}
}
Android Studio Logs表示NullPointerException错误发生在
httpstuff.setText(result);
在
new JSONTask().onPostExecute("http://samples.openweathermap.org/data/2.5/weather?q=Chicago&appid=93eea9a9277a0520d2f444c3ff8c62da");
private TextView httpstuff is a designated as a field but says that it is not initialized, but I use it in class JSONTask? Any ideas on why the exception is occurring? Thanks alot in advance!
答案 0 :(得分:1)
TextView httpstuff = (TextView)
删除第一个TextView。
在学习过程中始终尝试使用this.httpstuff
(或MainActivity.this.httpstuff
),直到您明白何时不使用this
httpstuff被指定为字段,但表示它未初始化
你正在使用Asynctask中的字段,是的,但你从未对其进行初始化,正如警告所说。
OnCreate有一个同名的局部变量