2017-09-07 28 views
-2

我一直在得到一個空指針異常錯誤。我查看了我的代碼,我不知道爲什麼我得到這個錯誤。當我編譯程序時填充空指針異常 - Android工作室

錯誤如下所示 空指針異常:試圖在空對象引用上調用虛方法int java.lang.String.length()。提前致謝。

EditText enterCity; 
TextView weatherView; 


public void onClick (View view) { 



    downloadAPIInfo task = new downloadAPIInfo(); 

    String APIKEY = "b4fabae83c89c469d7a458a230b7a267"; 
    String website = "http://api.openweathermap.org/data/2.5/weather?q="; 

    String url = website + enterCity.getText().toString() + APIKEY; 

    task.execute(url); 

    Log.i("User Entry", enterCity.getText().toString()); 



} 

public class downloadAPIInfo extends AsyncTask<String, Void, String> { 

    URL url; 
    HttpURLConnection httpURLConnection = null; 
    String result = ""; 

    @Override 
    protected String doInBackground(String... urls) { 

     try { 
      url = new URL(urls[0]); 

      httpURLConnection = (HttpURLConnection) url.openConnection(); 

      InputStream input = httpURLConnection.getInputStream(); 

      InputStreamReader reader = new InputStreamReader(input); 

      int data = reader.read(); 

      while(data != -1) { 

       char one = (char) data; 

       result += one; 

       data = reader.read(); 
      } 

      return result; 


     } catch (MalformedURLException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     return null; 
    } 

    //Onpostexecute interacts with the UI 
    @Override 
    protected void onPostExecute(String result) { 
     super.onPostExecute(result); 

     try { 

      String message = ""; 

      JSONObject object = new JSONObject(result); 

      String weatherInfo = object.getString("weather"); 

      Log.i("Weather content", weatherInfo); 


      JSONArray array = new JSONArray(weatherInfo); 

      for(int i = 0; i < array.length(); i++) { 

       JSONObject jsonPart = array.getJSONObject(i); 

       Log.i("main", jsonPart.getString("main")); 

       String main = ""; 
       String description = ""; 

       main = jsonPart.getString("main"); 
       description = jsonPart.getString("description"); 

       if(main != "" && description != "") { 

        message+= main + ":" + description + "\r\n"; 
       } 

      } 


      if(message != "") { 

       weatherView.setText(message); 
      } 

     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 


     //Log.i("WebsiteContent", result); 
    } 
} 



@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    enterCity = (EditText) findViewById(R.id.cityeditText); 
    weatherView = (TextView) findViewById(R.id.weathertextView); 


} 

}

+0

沒有完整的堆棧跟蹤異常,我們甚至不能猜測問題可能是什麼 – hardillb

回答

1

的JSONArray命名爲 '陣' 是你onPostExecute mehtod空。 很可能您的weatherInfo字符串爲空。

我建議你發佈完整的stacktrace以獲得更好的解釋。

+0

我想通了。謝謝 :) – mustyg123