【发布时间】:2018-05-20 21:24:32
【问题描述】:
我正在尝试使用单独的 java 类从 url 请求 JSON 以获取特定数据,如下所示。
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 并显示天气数据,但由于我没有得到任何纬度/经度,所以我无法显示任何内容。
我对代码量感到抱歉,但我不知道我在什么时候犯了错误,所以希望有人能够提供帮助。
谢谢。
【问题讨论】:
标签: java android json coordinates android-studio-2.3