2017-09-07 68 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