Search code examples
androidjson

Why is this code saying that there is no value for "callsign" in the JSONData from the FCC API I am using?


I am trying to access the FCC API as follows http://data.fcc.gov/lpfmapi/rest/v1/lat/36/long/-119?format=json&secondchannel=true

If you copy that URL you can see that it yields data some of which has a "callsign" designation. I want to return the callsign and frequency and for some reason I am getting an error saying there is no value for callsign. I am very new to JSONData so wondering what I did wrong! Any help would be amazing, thank you for reading!!!

HERE IS MY CODE FOR MAIN ACTIVITY

package com.dredaydesigns.radiostationfinder;

import android.R;
import android.app.Activity;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;


public class MainActivity extends Activity implements GoogleApiClient.ConnectionCallbacks {

    public static final String TAG = MainActivity.class.getSimpleName();
    private RadioData mRadioData;

    private GoogleApiClient mGoogleApiClient;
    private Location mLastLocation;

    TextView latitudeLabel;
    TextView longitudeLabel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_content);


        double latitude = 32;
        double longitude = -96;
        final RadioData[] mRadioData = new RadioData[1];
        String radioFinderURL = "http://data.fcc.gov/lpfmapi/rest/v1/lat/" + latitude + "/long/" + longitude + "?format=json&secondchannel=true";

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(radioFinderURL)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {

            }

            @Override
            public void onResponse(Response response) throws IOException {
                try {
                    String jsonData = response.body().string();
                    Log.v(TAG,jsonData);
                    if (response.isSuccessful()) {
                        mRadioData[0] = getCurrentDetails(jsonData);

                    }

                } catch (IOException e) {
                    Log.e(TAG, "Exception Caught: ", e);
                }
                catch(JSONException e){
                    Log.e(TAG, "Exception Caught:", e);
                }
            }
        });

    }

    private RadioData getCurrentDetails(String jsonData) throws JSONException {
        JSONObject radioData = new JSONObject(jsonData);
        String callSign = radioData.getString("callsign");
        Log.i(TAG, "From JSON: " + callSign);

        JSONObject currently = radioData.getJSONObject("frequency");
        RadioData radioFinder = new RadioData();


            return new RadioData();


    }

    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener((GoogleApiClient.OnConnectionFailedListener) this)
                .addApi(LocationServices.API)
                .build();


    }


    @Override
    public void onConnected(Bundle bundle) {
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                mGoogleApiClient);
        if (mLastLocation != null) {
            latitudeLabel.setText(String.valueOf(mLastLocation.getLatitude()));
            longitudeLabel.setText(String.valueOf(mLastLocation.getLongitude()));
        }
    }


    @Override
    public void onConnectionSuspended(int i) {

    }


}

and here is my code for RadioData.java

package com.dredaydesigns.radiostationfinder;

/**
 * Created by Andreas on 8/10/2015.
 */
public class RadioData {
    public String getCallSign() {
        return mCallsign;
    }

    public void setCallSign(String callsign) {
        mCallsign = callsign;
    }

    public double getFrequency() {
        return mFrequency;
    }

    public void setFrequency(double frequency) {
        mFrequency = frequency;
    }

    public int getChannel() {
        return mChannel;
    }

    public void setChannel(int channel) {
        mChannel = channel;
    }

    public double getLatitude() {
        return mLatitude;
    }

    public void setLatitude(double latitude) {
        mLatitude = latitude;
    }

    public double getLongitude() {
        return mLongitude;
    }

    public void setLongitude(double longitude) {
        mLongitude = longitude;
    }

    private String mCallsign;
    private double mFrequency;
    private int mChannel;
    private double mLatitude;
    private double mLongitude;



}

and here is my code for activity main XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:paddingLeft="@dimen/activity_horizontal_margin"
                android:paddingRight="@dimen/activity_horizontal_margin"
                android:paddingTop="@dimen/activity_vertical_margin"
                android:paddingBottom="@dimen/activity_vertical_margin"
                tools:context=".MainActivity"
                android:background="#ffffed">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Find Stations!"
        android:id="@+id/button"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:textColor="#010101"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/latitudeLabel"
        android:id="@+id/latitudeLabel"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginLeft="34dp"
        android:layout_marginStart="34dp"
        android:layout_marginTop="75dp"
        android:textColor="#010101"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/longitudeLabel"
        android:id="@+id/longitudeLabel"
        android:layout_alignTop="@+id/latitudeLabel"
        android:layout_alignLeft="@+id/button"
        android:layout_alignStart="@+id/button"
        android:layout_marginLeft="83dp"
        android:layout_marginStart="83dp"
        android:textColor="#010101"/>

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/listView"
        android:layout_above="@+id/button"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"/>

</RelativeLayout>

and finally here is what the logcat said, and the first line you can see it is receiving all the data so I guess I am not writing it properly to import the "callsign" value?

    08-10 23:13:42.115  28737-28753/com.dredaydesigns.radiostationfinder V/MainActivity﹕ {"status":"OK","responseTime":1777,"message":[],"decision":"PASSED.","interferingAnalysis":[{"channel":221,"frequency":92.1,"interferingChannels":[{"callsign":"KTBB-FM","interferenceChannel":221,"interferenceChannelType":"Same channel (cochannel)","actualDistance":80.1,"minDistanceReqd":119.0}]},{"channel":225,"frequency":92.9,"interferingChannels":[{"callsign":"KRMX","interferenceChannel":225,"interferenceChannelType":"Same channel (cochannel)","actualDistance":132.0,"minDistanceReqd":143.0},{"callsign":"KTYL-FM","interferenceChannel":226,"interferenceChannelType":"First-adjacent channel ","actualDistance":103.1,"minDistanceReqd":111.0}]},{"channel":260,"frequency":99.9,"interferingChannels":[{"callsign":"WACO-FM","interferenceChannel":260,"interferenceChannelType":"Same channel (cochannel)","actualDistance":144.3,"minDistanceReqd":203.0}]},{"channel":264,"frequency":100.7,"interferingChannels":[{"callsign":"KPXI","interferenceChannel":264,"interferenceChannelType":"Same channel (cochannel)","actualDistance":90.6,"minDistanceReqd":119.0},{"callsign":"KWRD-FM","interferenceChannel":264,"interferenceChannelType":"Same channel (cochannel)","actualDistance":187.4,"minDistanceReqd":203.0}]},{"channel":273,"frequency":102.5,"interferingChannels":[{"callsign":"KLJT","interferenceChannel":272,"interferenceChannelType":"First-adjacent channel ","actualDistance":80.1,"minDistanceReqd":84.0},{"callsign":"KBRQ","interferenceChannel":273,"interferenceChannelType":"Same channel (cochannel)","actualDistance":111.3,"minDistanceReqd":178.0}]},{"channel":277,"frequency":103.3,"interferingChannels":[{"callsign":"KJCS","interferenceChannel":277,"interferenceChannelType":"Same channel (cochannel)","actualDistance":128.5,"minDistanceReqd":143.0},{"callsign":"KESN","interferenceChannel":277,"interferenceChannelType":"Same channel (cochannel)","actualDistance":187.4,"minDistanceReqd":203.0}]},{"channel":285,"frequency":104.9,"interferingChannels":[{"callsign":"KZMP-FM","interferenceChannel":285,"interferenceChannelType":"Same channel (cochannel)","actualDistance":187.3,"minDistanceReqd":193.0}]},{"channel":289,"frequency":105.7,"interferingChannels":[{"callsign":"KYKX","interferenceChannel":289,"interferenceChannelType":"Same channel (cochannel)","actualDistance":129.2,"minDistanceReqd":193.0}]},{"channel":298,"frequency":107.5,"interferingChannels":[{"callsign":"KISX","interferenceChannel":297,"interferenceChannelType":"First-adjacent channel ","actualDistance":82.1,"minDistanceReqd":84.0},{"callsign":"KMVK","interferenceChannel":298,"interferenceChannelType":"Same channel (cochannel)","actualDistance":111.5,"minDistanceReqd":178.0}]},{"channel":299,"frequency":107.7},{"channel":300,"frequency":107.9}]}
    08-10 23:13:42.115  28737-28753/com.dredaydesigns.radiostationfinder E/MainActivity﹕ Exception Caught:
        org.json.JSONException: No value for callsign
                at org.json.JSONObject.get(JSONObject.java:38

9)
            at org.json.JSONObject.getString(JSONObject.java:550)
            at com.dredaydesigns.radiostationfinder.MainActivity.getCurrentDetails(MainActivity.java:80)
            at com.dredaydesigns.radiostationfinder.MainActivity.access$000(MainActivity.java:24)
            at com.dredaydesigns.radiostationfinder.MainActivity$1.onResponse(MainActivity.java:63)
            at com.squareup.okhttp.Call$AsyncCall.execute(Call.java:170)
            at com.squareup.okhttp.internal.NamedRunnable.run(NamedRunnable.java:33)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:818)

Solution

  • In this two line you are getting the value of "callsign" key.

    JSONObject radioData = new JSONObject(jsonData);
    String callSign = radioData.getString("callsign");
    

    This is your json data :

     //this is the starting of your jsondata means the radioData = this whole data.
     {
     "status": "OK",
     "responseTime": 1819,
     "message": [],
     "decision": "PASSED.",
     "interferingAnalysis": [
     {
      "channel": 222,
      "frequency": 92.3
    },
    {
      "channel": 239,
      "frequency": 95.7,
      "interferingChannels": [
        {
          "callsign": "KJFX",
          "interferenceChannel": 239,
          "interferenceChannelType": "Same channel (cochannel)",
          "actualDistance": 113.9,
          "minDistanceReqd": 143
        }
      ]
    },
    {
      "channel": 266,
      "frequency": 101.1,
      "interferingChannels": [
        {
          "callsign": "KWYE",
          "interferenceChannel": 266,
          "interferenceChannelType": "Same channel (cochannel)",
          "actualDistance": 118.1,
          "minDistanceReqd": 143
        }
      ]
    }
    ]
    }
    

    Now check inside the data the callsign key is present inside a jsonobject which is present inside a jsonarray named as "interferingChannels" and this jsonarray is present inside a jsonobject.

    Now if you want to get the value of "callsign" key then you need to use this code :

    JSONObject radioData = new JSONObject(jsonData);
    JSONArray jsonArray = radioData.getJSONArray("interferingAnalysis");
    for(int i =0; i<jsonArray.size(); i++){
    String callSign = radioData.getJsonObject(i).getJSONArraay("interferingChannels").getJSONObject(0).getString("callsign");
    }
    

    I hope this will work for you. May some spelling needs to be change. Please check that and let me know if you have any problem.

    Thanks :)