0

I'm getting an error when I try to get a non-static string in a static class.

this is the warning message "non static field cannot be referenced from a static context"

I want to get DOWNLOAD_URL String value to put in VIDEO_URL, but VIDEO_URL just get null value, how should I do that?

This is my code:

package com.sa.asd.ax

public class VideoProvider {

    String DOWNLOAD_URL;
    public static List<MediaInfo> buildMedia(String url) throws JSONException {

        if (null != mediaList) {
            return mediaList;
        }
        Map<String, String> urlPrefixMap = new HashMap<>();
        mediaList = new ArrayList<MediaInfo>();
        String VIDEO_URL = null;
        String mimeType = null;
         for (int k = 0; k < videoSpecs.length(); k++) {
            JSONObject videoSpec = videoSpecs.getJSONObject(k);
              if(TARGET_FORMAT.equals(videoSpec.getString(TAG_VIDEO_TYPE))){
                    String youtubeLink = urlPrefixMap.get(TARGET_FORMAT) + videoSpec.getString(TAG_VIDEO_URL);
                    YouTubeUriExtractor ytEx = new YouTubeUriExtractor(null{
                     @Override
                    public void onUrisAvailable(String videoId, String videoTitle, SparseArray<YtFile> ytFiles) {
                    if(ytFiles!=null){
                        int itag = 22; // a YouTube format identifier
                        DOWNLOAD_URL = ytFiles.get(itag).getUrl();
                                     }
                }
        };

    ytEx.execute(youtubeLink);
    VIDEO_URL = DOWNLOAD_URL;
    mimeType = videoSpec.getString(TAG_VIDEO_MIME);
    mediaList.add(buildMediaInfo(VIDEO_URL, mimeType));           
                            }
                        }

        return mediaList;
    }


}
Peanut
  • 3,753
  • 3
  • 31
  • 45
Arsyah
  • 1
  • 3

1 Answers1

0

buildMedia() is a static (class) method - it does not need an instance of VideoProvider to be invoked.

However, the string DOWNLOAD_URL is not static (it's an instance variable), and is tied to a specific instance, and thus it will fail.

What will happen if you do:

VideoProvider.buildMedia(someString);

Which DOWNLOAD_URL will you use in the method itself?

You can make the method unstatic, or make the String object static (class variable instead of instance variable) to solve it.

amit
  • 175,853
  • 27
  • 231
  • 333