gpt4 book ai didi

java - 在 Android 中使用日出/日落 REST API。如何正确传递获取到的位置坐标的URL?

转载 作者:太空宇宙 更新时间:2023-11-04 11:37:03 25 4
gpt4 key购买 nike

我正在制作一个 Android 应用程序,它获取用户位置的坐标,然后使用这些坐标与以下提供的 REST API 进行通信: this website

我对 JSON 解析和 REST API 相当陌生。我已经按照 this tutorial 使用了 AsyncTask、Spring 和 Jackson。

我的MainActivity.java看起来像这样 -

package com.gamecodeschool.whereintheworld;

import android.content.Context;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.location.Criteria;
import android.location.Location;

import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import android.os.AsyncTask;

public class MainActivity extends AppCompatActivity implements LocationListener {

private TextView txtLat;
private TextView txtLong;
private TextView txtSource;
private LocationManager locationManager;
private String provider;

@Override
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
new HttpRequestTask().execute();
setContentView(R.layout.activity_main);
txtLat = (TextView) findViewById(R.id.txtLat);
txtLong = (TextView) findViewById(R.id.txtLong);
txtSource = (TextView) findViewById(R.id.txtSource);

//Initialize locationManager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);

//initialize the location
if(location != null){
txtSource.setText("Source = " +provider);
onLocationChanged(location);
}

}
//start updates when app starts/resumes
@Override
protected void onResume() {
super.onResume();
new HttpRequestTask().execute();
locationManager.requestLocationUpdates
(provider, 500, 1, this);
}

@Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}

@Override
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lng = location.getLongitude();
txtLat.setText(String.valueOf(lat));
txtLong.setText(String.valueOf(lng));
txtSource.setText("Source = " + provider);
}

public String getCoordinates(Location location)
{
double latitude = location.getLatitude();
double longitude = location.getLongitude();

return ("lat="+latitude+"&lng="+longitude);

}

@Override
public void onStatusChanged(String provider,
int status, Bundle extras) {
txtSource.setText("Source = " + provider);
}
@Override
public void onProviderEnabled(String provider) {

txtSource.setText("Source = " + provider);
}
@Override
public void onProviderDisabled(String provider) {

txtSource.setText("Source = " + provider);
}

//USER DEFINED CLASS
private class HttpRequestTask extends AsyncTask<Void, Void, sunrisedata> {



@Override
protected sunrisedata doInBackground(Void... params) {
try {


final String url = "http://api.sunrise-sunset.org/json?";
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
sunrisedata greeting = restTemplate.getForObject(url, sunrisedata.class);
return greeting;
} catch (Exception e) {
Log.e("MainActivity", e.getMessage(), e);
}

return null;
}

@Override
protected void onPostExecute(sunrisedata greeting) {
TextView greetingIdText = (TextView) findViewById(R.id.txtSunrise);

greetingIdText.setText(greeting.getSunrise());

}

}


}

在MainActivity.java的这一部分

final String url = "http://api.sunrise-sunset.org/json?";

我想传递从这部分代码获得的坐标 -

public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lng = location.getLongitude();
txtLat.setText(String.valueOf(lat));
txtLong.setText(String.valueOf(lng));
txtSource.setText("Source = " + provider);
}

因为根据 REST API 文档,GET 请求 URL 应该采用这种格式 -

http://api.sunrise-sunset.org/json?lat=36.7201600&lng=-4.4203400

如何检索纬度和经度并将其附加到 HttpRequestTask 类方法中的 URL -

protected sunrisedata doInBackground(Void... params) 

到目前为止,logcat 错误看起来像这样 -

04-03 01:56:35.231 13842-1925/com.gamecodeschool.whereintheworld E/MainActivity: Could not read JSON: Unrecognized token 'Array': was expecting ('true', 'false' or 'null')
at [Source: buffer(com.android.okio.GzipSource@1713350c).inputStream(); line: 1, column: 11]; nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'Array': was expecting ('true', 'false' or 'null')
at [Source: buffer(com.android.okio.GzipSource@1713350c).inputStream(); line: 1, column: 11]
org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Unrecognized token 'Array': was expecting ('true', 'false' or 'null')
at [Source: buffer(com.android.okio.GzipSource@1713350c).inputStream(); line: 1, column: 11]; nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'Array': was expecting ('true', 'false' or 'null')
at [Source: buffer(com.android.okio.GzipSource@1713350c).inputStream(); line: 1, column: 11]
at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.readInternal(MappingJackson2HttpMessageConverter.java:126)
at org.springframework.http.converter.AbstractHttpMessageConverter.read(AbstractHttpMessageConverter.java:147)
at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:76)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:484)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:439)
at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:237)
at com.gamecodeschool.whereintheworld.MainActivity$HttpRequestTask.doInBackground(MainActivity.java:111)
at com.gamecodeschool.whereintheworld.MainActivity$HttpRequestTask.doInBackground(MainActivity.java:99)
at android.os.AsyncTask$2.call(AsyncTask.java:292)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'Array': was expecting ('true', 'false' or 'null')
at [Source: buffer(com.android.okio.GzipSource@1713350c).inputStream(); line: 1, column: 11]
at com.fasterxml.jackson.core.JsonParser._constructError(JsonParser.java:1524)
at com.fasterxml.jackson.core.base.ParserMinimalBase._reportError(ParserMinimalBase.java:557)
at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._reportInvalidToken(UTF8StreamJsonParser.java:3094)
at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._handleUnexpectedValue(UTF8StreamJsonParser.java:2339)
at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._nextTokenNotInObject(UTF8StreamJsonParser.java:817)
at com.fasterxml.jackson.core.json.UTF8StreamJsonParser.nextToken(UTF8StreamJsonParser.java:697)
at com.fasterxml.jackson.databind.ObjectMapper._initForReading(ObjectMapper.java:3031)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:2978)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2158)
at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.readInternal(MappingJackson2HttpMessageConverter.java:123)
... 13 more
04-03 01:56:35.232 13842-13842/com.gamecodeschool.whereintheworld D/AndroidRuntime: Shutting down VM
04-03 01:56:35.233 13842-13842/com.gamecodeschool.whereintheworld E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.gamecodeschool.whereintheworld, PID: 13842
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.gamecodeschool.whereintheworld.sunrisedata.getSunrise()' on a null object reference
at com.gamecodeschool.whereintheworld.MainActivity$HttpRequestTask.onPostExecute(MainActivity.java:124)
at com.gamecodeschool.whereintheworld.MainActivity$HttpRequestTask.onPostExecute(MainActivity.java:99)
at android.os.AsyncTask.finish(AsyncTask.java:636)
at android.os.AsyncTask.access$500(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5294)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
04-03 01:56:36.027 13842-2035/com.gamecodeschool.whereintheworld E/MainActivity: Could not read JSON: Unrecognized token 'Array': was expecting ('true', 'false' or 'null')
at [Source: buffer(com.android.okio.GzipSource@3969795b).inputStream(); line: 1, column: 11]; nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'Array': was expecting ('true', 'false' or 'null')
at [Source: buffer(com.android.okio.GzipSource@3969795b).inputStream(); line: 1, column: 11]
org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Unrecognized token 'Array': was expecting ('true', 'false' or 'null')
at [Source: buffer(com.android.okio.GzipSource@3969795b).inputStream(); line: 1, column: 11]; nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'Array': was expecting ('true', 'false' or 'null')
at [Source: buffer(com.android.okio.GzipSource@3969795b).inputStream(); line: 1, column: 11]
at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.readInternal(MappingJackson2HttpMessageConverter.java:126)
at org.springframework.http.converter.AbstractHttpMessageConverter.read(AbstractHttpMessageConverter.java:147)
at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:76)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:484)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:439)
at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:237)
at com.gamecodeschool.whereintheworld.MainActivity$HttpRequestTask.doInBackground(MainActivity.java:111)
at com.gamecodeschool.whereintheworld.MainActivity$HttpRequestTask.doInBackground(MainActivity.java:99)
at android.os.AsyncTask$2.call(AsyncTask.java:292)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'Array': was expecting ('true', 'false' or 'null')
at [Source: buffer(com.android.okio.GzipSource@3969795b).inputStream(); line: 1, column: 11]
at com.fasterxml.jackson.core.JsonParser._constructError(JsonParser.java:1524)
at com.fasterxml.jackson.core.base.ParserMinimalBase._reportError(ParserMinimalBase.java:557)
at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._reportInvalidToken(UTF8StreamJsonParser.java:3094)
at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._handleUnexpectedValue(UTF8StreamJsonParser.java:2339)
at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._nextTokenNotInObject(UTF8StreamJsonParser.java:817)
at com.fasterxml.jackson.core.json.UTF8StreamJsonParser.nextToken(UTF8StreamJsonParser.java:697)
at com.fasterxml.jackson.databind.ObjectMapper._initForReading(ObjectMapper.java:3031)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:2978)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2158)
at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.readInternal(MappingJackson2HttpMessageConverter.java:123)
... 13 more

据我所知,出现此错误是因为正确的 URL 以及纬度和经度未传递到网站。显然,该应用程序在手机上运行时也会崩溃。

我按照 spring 网站上的教程创建的另一个类是 - sunrisedata.java 用于存储获得的 JSON 响应,如下所示 -

package com.gamecodeschool.whereintheworld;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;


@JsonIgnoreProperties(ignoreUnknown=true)
public class sunrisedata {

private String results;

public String getSunrise(){

return this.results;
}

}

请告诉我如何正确地将 MainActivity 类中获得的纬度和经度值传递到 HttpRequestTask 类中的 url,我只想从 JSON 检索日出数据并忽略所有其他字段。

最佳答案

获取用户位置是异步发生的,这意味着您必须等到位置从 LocationManager 返回给您之后才能发出获取日出/日落数据的请求。

现在,您在 onResume() 中请求日出/子集数据,这是不正确的。当您在此处执行请求时,您可能还没有位置数据。

您似乎想要在 onLocationChanged() 中获取日出/日落数据。此方法将包含您需要添加到 URL 的位置信息。

关于java - 在 Android 中使用日出/日落 REST API。如何正确传递获取到的位置坐标的URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43173309/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com