2017-02-25 19 views
0

私は天候を決定するために、ボタンをクリックしたときに、私は次のよう..オープン天候APIとそのクラッシュを使用して天気アプリを作成しているlogcatJSON天気APIエラー

以下
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference 
                      at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116) 
                      at org.json.JSONTokener.nextValue(JSONTokener.java:94) 
                      at org.json.JSONObject.<init>(JSONObject.java:156) 
                      at org.json.JSONObject.<init>(JSONObject.java:173) 
                      at com.example.hemantj.weather.MainActivity$DownloadTask.onPostExecute(MainActivity.java:133) 
                      at com.example.hemantj.weather.MainActivity$DownloadTask.onPostExecute(MainActivity.java:92) 
                      at android.os.AsyncTask.finish(AsyncTask.java:651) 
                      at android.os.AsyncTask.access$500(AsyncTask.java:180) 
                      at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668) 
                      at android.os.Handler.dispatchMessage(Handler.java:102) 
                      at android.os.Looper.loop(Looper.java:148) 
                      at android.app.ActivityThread.main(ActivityThread.java:5451) 
                      at java.lang.reflect.Method.invoke(Native Method) 
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

は私が使用している...コードですアンドロイドTARGET SDK 25および23としてMIN SDK ..そうマシュマロので誤差があり、あなたがあなたのAPI keyを逃している

weather.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 

      if(checkSelfPermission(Manifest.permission.INTERNET) == PackageManager.PERMISSION_GRANTED){ 

       try { 

        //to hide the keyboard after pressing the button 
        InputMethodManager manager = 
          (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); 
        manager.hideSoftInputFromInputMethod(weatherInput.getWindowToken(),0); 

        DownloadTask downloadTask = new DownloadTask(); 

        //used to encode the entered input for url.. for example San Fransisco appears in url 
        //as San%20Fransisco ... and to enable that we use the encoder... 
        String encodedCity = URLEncoder.encode(city,"UTF-8"); 

        downloadTask.execute("http://api.openweathermap.org/data/2.5/weather?q=" + encodedCity + "&APPID=0a7808bb8061814df9b6d5fc88d58b8f"); 

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

      } 
      else{ 
       if(shouldShowRequestPermissionRationale(Manifest.permission.INTERNET)){ 

        Toast.makeText(MainActivity.this, 
          "Internet permissions are necessary",Toast.LENGTH_LONG).show(); 

       } 

       requestPermissions(new String[]{Manifest.permission.INTERNET},INTERNET_CODE); 
      } 
     } 
    }); 
} 

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

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

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

     try { 
      url = new URL(urls[0]); 
      httpURLConnection = (HttpURLConnection) url.openConnection(); 
      InputStream in = httpURLConnection.getInputStream(); 
      InputStreamReader reader = new InputStreamReader(in); 
      int data = reader.read(); 
      while(data != -1){ 
       char current = (char) data; 
       result += current; 

       data = reader.read(); 
      } 
      return result; 

     } 
     //combined the exceptions MalformedURL and IOException to a common to display a toast msg 
     catch (Exception e) { 
      e.printStackTrace(); 
     } 

     return null; 

    } 

    @Override 
    protected void onPostExecute(String result) { 
     super.onPostExecute(result); 

     try { 

      String message = ""; 

      JSONObject jsonObject = new JSONObject(result); 

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

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

      JSONArray arr = new JSONArray(weatherInfo); 

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

       JSONObject jsonPart = arr.getJSONObject(i); 

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

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

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

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

       } 

      } 

      if (message != "") { 

       weatherReport.setText(message); 

      } else { 

       Toast.makeText(getApplicationContext(), "Could not find weather", Toast.LENGTH_LONG).show(); 

      } 


     } catch (JSONException e) { 

      Toast.makeText(getApplicationContext(), "Could not find weather", Toast.LENGTH_LONG).show(); 

     } 

    } 
} 

答えて

0

...権限に関連する何かが間違っている場合も、それを指摘..だから関与しています返され、String weatherInfo = jsonObject.getString("weather");はnullです。したがって、配列の.lengthを取得しようとすると、nullになります。別のStringオブジェクトを以下のように作成します。

String apiKey = "Put API key here";その後

変更:この

downloadTask.execute("http://api.openweathermap.org/data/2.5/weather?q=" + encodedCity + "&appid=" + apiKey);

この

downloadTask.execute("http://api.openweathermap.org/data/2.5/weather?q=" + encodedCity); 

をまた、あなたはあなたのマニフェストのインターネットアクセス権を持っていることを確認してください。

<uses-permission android:name="android.permission.INTERNET" />

+0

どこにキーを置くのですか? –

+0

downloadTask.execute( "http://api.openweathermap.org/data/2.5/weather?q=" + encodedCity + "&APPID = 0a7808bb8061814df9b6d5fc88d58b8f");私はこれを試みたが、それはまだ同じエラーを示して..私はそれがアクセス許可と何かをしなければならないと思う..Plsそれを..私は12時間以上、この問題にこだわっているように:( –

+1

あなたは必要ありません'Manifest.permission.INTERNET'が許可されているかどうかをチェックするには、[通常の](https://developer.android.com/guide/topics/permissions/normal-permissions.html)権限とみなされます。 –