使用 json 和位置显示来自天气 API 的数据

Using json and location to display data from a Weather API

我正在尝试从 url 请求 JSON 以使用单独的 java class.

获取特定数据,如下所示
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  
    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;
}
}

然后在另一个 activity 我正在获取经度和纬度并将其绑定到文本以显示它:

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();
    }

之后我使用此代码将信息发送到另一个应用程序并启动 activity:

      public void sendLocation(View view) {
    Intent coordinates = new Intent(this,MainActivity.class);
    coordinates.putExtra("lat", lat);
    coordinates.putExtra("longi", longi);
    startActivity(coordinates);
}

然后在主要 activity 我正在尝试接收数据并显示它但我发现并发出当在以下代码中设置纬度和经度时数据尚未发送或接收的问题0 纬度和经度仍 class 化为空并显示错误消息。

 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 并显示天气数据,但由于我没有得到任何 lat/longi 我无法显示任何内容。

对于代码量,我很抱歉,但我不知道我在哪一点上犯了错误,所以希望有人能提供帮助。

谢谢。

我看到了几个问题,但我已经有一段时间没搞定了 Android java。

  1. 为什么要将视图传递给 SendLocation() 和 getCoordinates()?每个 Activity 都应该控制自己的屏幕使用。

  2. 您在 onClick() 处理程序中检索 MainActivity 意图。相反,这应该在主线中,来自 OnCreate()、onNewIntent() 等。我的猜测是这就是您的问题的原因。如果你在这个activity的开头捕获MainActivity Intent(),你可以控制是否继续处理(例如,如果传递0)。

此外,您没有显示这些 Activity 中的任何一个或 getJSONFromURL class 是如何被调用的,这可能会对您看到的内容产生影响。

HTH,吉姆