【问题标题】:Using json and location to display data from a Weather API使用 json 和 location 显示来自 Weather API 的数据
【发布时间】: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


    【解决方案1】:

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

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

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

    此外,您没有展示如何调用这些 Activity 或 getJSONFromURL 类,这可能会影响您看到的内容。

    HTH,吉姆

    【讨论】:

    • 当我将意图放在 OnCreate() 中时,应用程序崩溃了,我认为这是因为 OnCreate 总是在收集所有其他数据之前首先执行,因此如果在另一个活动中未声明该位置没有要发送的数据...但这只是一个理论,因为我也不是经验丰富的 Android/Java 用户。
    • Konradst,如果 getCoordinates() 是 MainActivity 的一部分,则在其 onCreate() 中您应该能够执行以下操作:@Override public void onCreate(Bundle icicle) { super.onCreate(icicle );意图 i = getIntent();捆绑附加服务 = i.getExtras(); lat = extras.getDouble("lat"); longi = extras.getDouble("longi");获取坐标();只需确保将 lat & longi 设置为您的活动中的全局变量,因为 onClickListeners() 无权访问该方法中的“本地”变量。如果你不能让它运行,请发布代码
    • 毕竟这不是问题。问题是解析器,我有多个请求,而我应该只有 1 个请求并将变量替换为 0。无论如何,谢谢你的帮助。
    猜你喜欢
    • 1970-01-01
    • 2022-12-23
    • 2016-11-04
    • 1970-01-01
    • 2021-06-04
    • 2020-02-09
    • 1970-01-01
    • 2021-10-17
    • 2020-11-27
    相关资源
    最近更新 更多