简体   繁体   中英

Using json and location to display data from a Weather API

I am trying to request a JSON froM a url to get specific data as shown below using separate 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 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;
}
}

Then in another another activity I am getting longitude and latitude and bind it to text to display it:

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

Afterwards I send information to another application using this code and start the activity:

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

Then in the main activity I am trying to receive data and display it yet I caught and issue that the data is either not sent or received yet when the latitude and longitude are set in the following code to 0 the lat and longi are still classified as null and display and error message.

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

The application is supposed to use the collected latitude and longitude to access url and display the weather data but as I don't get any lat/longi I cannot show anything.

I am sorry for the amount of code but I have no clue at which point I have managed to make a mistake so hopefully someone will be able to help.

Thanks.

I see a couple of issues, but it's been a while since I messed with Android java.

  1. Why are you passing a View to SendLocation() and getCoordinates()? Each Activity should control their own screen usage.

  2. You retrieve your MainActivity intent inside an onClick() handler. Instead, this should be in the main line, either from OnCreate(), onNewIntent(), etc. My guess is that this is the cause of your issue. If you capture the MainActivity Intent() at the start of this activity, you can control whether to continue processing or not (if 0's are passed for example).

Also, you don't show how any of these Activity's or the getJSONFromURL class are invoked, which could have an impact on what you see.

HTH, Jim

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM