簡體   English   中英

org.json.JSONException:輸入的結尾(字符為0)

[英]org.json.JSONException: End of input at character 0 of

我遵循了以下教程,但是我的代碼出現系統錯誤: http : //www.informit.com/articles/article.aspx?p=2154675&seqNum=4

這是所有錯誤:

W/EGL_emulation: eglSurfaceAttrib not implemented
W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x7f651f4e3780, error=EGL_SUCCESS
W/DefaultRequestDirector: Authentication error: Unable to respond to any of these challenges: {}
W/System.err: org.json.JSONException: End of input at character 0 of 
W/System.err:     at org.json.JSONTokener.syntaxError(JSONTokener.java:450)
W/System.err:     at org.json.JSONTokener.nextValue(JSONTokener.java:97)
W/System.err:     at org.json.JSONObject.(JSONObject.java:156)
W/System.err:     at org.json.JSONObject.(JSONObject.java:173)
W/System.err:     at com.example.theol.opsc7312_assign2_14001515_theolin_naidoo.MainActivity$ReadJSONFeed.onPostExecute(MainActivity.java:74)
W/System.err:     at com.example.theol.opsc7312_assign2_14001515_theolin_naidoo.MainActivity$ReadJSONFeed.onPostExecute(MainActivity.java:46)
W/System.err:     at android.os.AsyncTask.finish(AsyncTask.java:636)
W/System.err:     at android.os.AsyncTask.access$500(AsyncTask.java:177)
W/System.err:     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
W/System.err:     at android.os.Looper.loop(Looper.java:135)
W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5254)
W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
W/System.err:     at java.lang.reflect.Method.invoke(Method.java:372)
W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

Application terminated.

這是我的代碼:

import android.os.Bundle;
import android.app.Activity;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.view.View;
import org.apache.http.client.methods.HttpPost;
import org.json.JSONException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.client.HttpClient;
import org.apache.http.HttpResponse;
import org.apache.http.HttpEntity;
import java.io.InputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import android.os.AsyncTask;
import org.json.JSONObject;
import org.apache.http.StatusLine;
import org.json.JSONArray;
import java.text.NumberFormat;

public class MainActivity extends Activity {
    String city="";

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

        Button submitButton = (Button)this.findViewById(R.id.submit_btn);

        submitButton.setOnClickListener(new Button.OnClickListener(){
            public void onClick(View v) {
                String country="";
                EditText cityName = (EditText) findViewById(R.id.city_name);
                city=cityName.getText().toString();

                String url="http://api.openweathermap.org/data/2.5/weather?q="+city;
                new ReadJSONFeed().execute(url);

            }
        });
    }
    private class ReadJSONFeed extends AsyncTask<String, String, String> {
        protected void onPreExecute() {}
        @Override
        protected String doInBackground(String... urls) {
            HttpClient httpclient = new DefaultHttpClient();
            StringBuilder builder = new StringBuilder();
            HttpPost httppost = new HttpPost(urls[0]);
            try {
                HttpResponse response = httpclient.execute(httppost);
                StatusLine statusLine = response.getStatusLine();
                int statusCode = statusLine.getStatusCode();
                if (statusCode == 200) {
                    HttpEntity entity = response.getEntity();
                    InputStream content = entity.getContent();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        builder.append(line);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return builder.toString();
        }
        protected void onPostExecute(String result) {
            String weatherInfo="Weather Report of "+city +" is: \n";
            try{

                JSONObject jsonObject = new JSONObject(result);
                JSONObject jscoordObject = new JSONObject(jsonObject.getString("coord"));
                weatherInfo+="Longitude: "+jscoordObject.getString("lon")+"\n";
                weatherInfo+="Latitude: "+jscoordObject.getString("lat")+"\n";
                JSONArray jsweatherObject = new JSONArray(jsonObject.getString("weather"));
                JSONObject jweatherObject = jsweatherObject.getJSONObject(0);
                weatherInfo+="Clouds: "+jweatherObject.getString("description")+"\n";
                JSONObject jsmainObject = new JSONObject(jsonObject.getString("main"));
                weatherInfo+="Humidity: "+jsmainObject.getString("humidity")+"% \n";
                weatherInfo+="Atmospheric Pressure: "+jsmainObject.getString("pressure")+"hPa \n";
                float temp=Float.parseFloat(jsmainObject.getString("temp"));
                temp = temp - (float) 273.15;
                NumberFormat df = NumberFormat.getNumberInstance();
                df.setMaximumFractionDigits(2);
                weatherInfo+="Temperature: "+ String.valueOf(df.format(temp)) +" C\n";
                JSONObject jswindObject = new JSONObject(jsonObject.getString("wind"));
                weatherInfo+="Wind Speed: "+jswindObject.getString("speed")+"mps \n";
            }
            catch (JSONException e) {
                e.printStackTrace();
            }
            TextView resp = (TextView) findViewById(R.id.response);
            if(weatherInfo.trim().length() >0 )
                resp.setText(weatherInfo);
            else
                resp.setText("Sorry no match found");
        }
    }
}

基於該錯誤,您不會得到JSON,這可能意味着您收到了一些HTTP錯誤。

如果在嘗試解析result之前Log result的值,您會更容易看到。


但是,您應該意識到這一點。

“如果您使用的是免費或付費計划,則要訪問API,您需要注冊一個API密鑰。”
-http://openweathermap.org/api

請參閱此處以使用API​​密鑰

換句話說,獲取API密鑰,然后將其附加到您的URL。 例如

String API_KEY = "XXXXxxxx";
String url = "http://.../weather?q=" + city + "&APPID=" + API_KEY;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM