![](/img/trans.png)
[英]Android…Not getting JSON respone from darksky weather API using Okhttp
[英]Using json and location to display data from a Weather API
我正在尝试通过URL请求JSON来获取特定数据,如下所示,使用单独的Java类。
package com.example.user.test4;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.util.Log;
/**
* Created by user on 05/12/2017.
*/
public class Parser {
// the below line is for making debugging easier
final String TAG = "Parser.java";
// where the returned json data from service will be stored when downloaded
static String json = "";
public String getJSONFromUrl(String url) {
//// TODO: 05/12/2017 https://stackoverflow.com/questions/4308554/simplest-way-to-read-json-from-a-url-in-java
try {
// this code block represents/configures a connection to your REST service
// it also represents an HTTP 'GET' request to get data from the REST service, not POST!
URL u = new URL(url);
HttpURLConnection restConnection = (HttpURLConnection) u.openConnection();
restConnection.setRequestMethod("GET");
restConnection.setRequestProperty("Content-length", "main");
restConnection.setRequestProperty("Content-length", "sys");
restConnection.setRequestProperty("Content-length", "weather");
restConnection.setUseCaches(false);
restConnection.setAllowUserInteraction(false);
restConnection.setConnectTimeout(10000);
restConnection.setReadTimeout(10000);
restConnection.connect();
int status = restConnection.getResponseCode();
// switch statement to catch HTTP 200 and 201 errors
switch (status) {
case 200:
case 201:
// live connection to your REST service is established here using getInputStream() method
BufferedReader br = new BufferedReader(new InputStreamReader(restConnection.getInputStream()));
// create a new string builder to store json data returned from the REST service
StringBuilder sb = new StringBuilder();
String line;
// loop through returned data line by line and append to stringbuilder 'sb' variable
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
// remember, you are storing the json as a stringy
try {
json = sb.toString();
} catch (Exception e) {
Log.e(TAG, "Error parsing data " + e.toString());
}
// return JSON String containing data to activity (or whatever your activity is called!)
return json;
}
// HTTP 200 and 201 error handling from switch statement
} catch (MalformedURLException ex) {
Log.e(TAG, "Malformed URL ");
} catch (IOException ex) {
Log.e(TAG, "IO Exception ");
}
return null;
}
}
然后在另一个活动中,我正在获取经度和纬度并将其绑定到文本以显示它:
LocationManager locationManager = (LocationManager)
this.getSystemService(Context.LOCATION_SERVICE);
// Use GPS provider to get last known location
String locationProvider = LocationManager.GPS_PROVIDER;
Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
if (lastKnownLocation == null)
{
// if no last location is available set lat/long to Lincoln Location
lat = 53.228029;
longi = -0.546055;
}
else
{
// if last location exists then get/set the lat/long
lat = lastKnownLocation.getLatitude();
longi = lastKnownLocation.getLongitude();
}
之后,我使用此代码将信息发送到另一个应用程序并开始活动:
public void sendLocation(View view) {
Intent coordinates = new Intent(this,MainActivity.class);
coordinates.putExtra("lat", lat);
coordinates.putExtra("longi", longi);
startActivity(coordinates);
}
然后在主要活动中,我试图接收数据并显示它,但我仍然捕获并发出以下问题:当在以下代码中将纬度和经度设置为0时,纬度和经度仍被分类为null并显示和错误消息。
public void getCoordinates(View view) {
// FIXME: 05/12/2017
final Button coordinates = (Button) findViewById(R.id.getCoordinates);
final Button displayData = (Button) findViewById(R.id.displayData);
coordinates.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
getLocation = MainActivity.this.getIntent();
extras = getLocation.getExtras();
lat = extras.getDouble("lat");
longi = extras.getDouble("longi");
//Checking if there is data stored in the doubles, if not the user will be warned
if (lat == null && longi == null) {
Toast.makeText(MainActivity.this, "No Data recorded, please use permissions", Toast.LENGTH_SHORT).show();
} else {
displayData.setVisibility(View.VISIBLE);
}
该应用程序应该使用收集到的纬度和经度来访问url并显示天气数据,但是由于我没有得到任何纬度/经度,因此我什么也无法显示。
我对代码的数量感到抱歉,但是我不知道在哪一点上我已经犯了一个错误,因此希望有人能够提供帮助。
谢谢。
我看到了几个问题,但是自从搞砸Android Java以来已经有一段时间了。
为什么将View传递给SendLocation()和getCoordinates()? 每个活动都应控制自己的屏幕使用情况。
您可以在onClick()处理函数中检索MainActivity意图。 取而代之的是,这应该在OnLine(),onNewIntent()等主行中。我的猜测是这是导致问题的原因。 如果在此活动开始时捕获MainActivity Intent(),则可以控制是否继续处理(例如,如果传递了0,则继续)。
此外,您不会显示如何调用这些Activity或getJSONFromURL类,这可能会对您看到的内容产生影响。
HTH,吉姆
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.