2017-02-14 67 views
0

不太確定爲什麼我得到一個NullPointerException,Java新手,所以任何幫助將不勝感激!NullPointerException,簡單的錯誤?

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中記錄說,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! 
+1

你'陰影httpstuff' –

回答

1
TextView httpstuff = (TextView) 

刪除第一個TextView的。

始終嘗試使用this.httpstuff(或MainActivity.this.httpstuff),而學習,直到你明白的時候不要使用this

httpstuff被指定爲一個字段,但表示,它沒有被初始化

你在Asynctask中使用這個領域,是的,但你從來沒有初始化它,正如警告所說。

OnCreate中有

+0

感謝您的幫助同名的局部變量!我刪除了onCreate中的第一個textview,但仍然在相同的行中得到異常,對不起,如果我失去了明顯的東西。 –

+0

那麼,findViewById返回null。我不認爲你可以將文本設置爲空字符串。你可以通過代碼把打印語句看到會發生什麼 –

+0

使用View.onClickListener()解決這個問題? –