Jump to content
carlosguerradev

Youtube API Está-me a dar null

Recommended Posts

carlosguerradev

Boas noites!

Estava a fazer um programa que mostrava os dados dos utilizadores do youtube (Subs,Views)

Mas por algum motivo quando vou por o programa a funcionar dá-me sempre null !

Eu nao sei onde o programa está a falhar alguém me pode ajudar ?

Ps: Estou a utilizar Javafx

Erro

java.lang.NullPointerException
	at application.ConceptController.lambda$2(ConceptController.java:74)
	at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
	at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
	at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
	at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
	at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
	at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
	at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
	at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
	at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
	at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
	at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
	at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
	at javafx.event.Event.fireEvent(Event.java:198)
	at javafx.scene.Scene$ClickGenerator.postProcess(Scene.java:3470)
	at javafx.scene.Scene$ClickGenerator.access$8100(Scene.java:3398)
	at javafx.scene.Scene$MouseHandler.process(Scene.java:3766)
	at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
	at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
	at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
	at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:381)
	at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
	at java.security.AccessController.doPrivileged(Native Method)
	at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$354(GlassViewEventHandler.java:417)
	at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
	at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:416)
	at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
	at com.sun.glass.ui.View.notifyMouse(View.java:937)
	at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
	at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
	at java.lang.Thread.run(Thread.java:745)

Código

package application;

import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Pane;
import javafx.stage.Window;

import java.io.IOException;
import java.math.BigInteger;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;

import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.ChannelListResponse;
import com.jfoenix.controls.JFXTextField;
import javafx.event.ActionEvent;

//YOutube

import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.Channel;
import com.google.api.services.youtube.model.ChannelListResponse;


public class ConceptController implements Initializable {

	private YouTube youtube;


	@FXML
	private JFXTextField msg;

	@FXML
	private Pane moveon;

	@FXML
	private AnchorPane allbase;

	@FXML
	void funcion(ActionEvent event) {
		System.out.println(msg.getText());
		msg.clear();
	}

	private double mx, my;

	@FXML
	public void moveonDragMousePressed(MouseEvent m){
	}

	private void drag() {
		moveon.setOnMousePressed(me -> {
			Window window = allbase.getScene().getWindow();
			mx = window.getX() - me.getScreenX();
			my = window.getY() - me.getScreenY();
		});
		moveon.setOnMouseDragged(me -> {
			Window window = allbase.getScene().getWindow();
			window.setX(me.getScreenX() + mx);
			window.setY(me.getScreenY() + my);
		});
		allbase.setOnMouseClicked(me ->  {
			allbase.requestFocus();

			try {
				YouTubeChannel youTubeChannel = getDataFor("andreplays15"); 	
				System.out.println("Canal:" + youTubeChannel.getChannelName());//Null Aqui (java.lang.NullPointerException)
				//System.out.println("§fSubs: §a" + youTubeChannel.getSubCount());
				//System.out.println("§fVideos: §a" + youTubeChannel.getVideosCount());
				//System.out.println("§fViews: §a" + youTubeChannel.getViewsCount());
								
			} catch (Exception exce) {
				exce.printStackTrace();
			}


		});		
	}

	@Override
	public void initialize(URL location, ResourceBundle resources) {

		youtube = new YouTube.Builder(new NetHttpTransport(), new JacksonFactory(),
				request -> {
				}).setApplicationName("Andreplays15").build();


		System.out.println("");
		System.out.println("INIT: ConceptController.java");
		drag();
		msg.setStyle("-fx-text-fill: white;");
		System.out.println("INIT: --> Success on initializing ConceptController.java");
	}


	public YouTubeChannel getDataFor(String channelId) throws IOException {
		YouTube.Channels.List channelRequest = youtube.channels().list("snippet,statistics");
		channelRequest.setId(channelId);
		channelRequest.setKey("AIzaSyANycARfjYBF_EaLpC_9rLSFs2nt9GAH7c");
		ChannelListResponse channelResult = channelRequest.execute();

		List<Channel> channelsList = channelResult.getItems();
		if (channelsList.isEmpty()) {
			return null;
		}
		return new YouTubeChannel(channelsList.get(0));
	}

	public class YouTubeChannel {

		private Channel channel;

		public YouTubeChannel(Channel channel) {
			this.channel = channel;
		}

		public Channel getChannel() {
			return channel;
		}

		public BigInteger getSubCount() {
			return channel.getStatistics().getSubscriberCount();
		}

		public BigInteger getVideosCount() {
			return channel.getStatistics().getVideoCount();
		}

		public BigInteger getViewsCount() {
			return channel.getStatistics().getViewCount();
		}

		public String getChannelName() {
			return channel.getSnippet().getTitle();
		}

		public String getChannelDesc() {
			return channel.getSnippet().getDescription();
		}
	}


}

 

Share this post


Link to post
Share on other sites
carlosguerradev

System.out.println("Canal:" + youTubeChannel.getChannelName());//Null Aqui (java.lang.NullPointerException)

5 horas atrás, HappyHippyHippo disse:

qual é a linha 74 ?

System.out.println("Canal:" + youTubeChannel.getChannelName());//Null Aqui (java.lang.NullPointerException)

Share this post


Link to post
Share on other sites
HappyHippyHippo

o erro é bem claro se tirares o código que não interessa ao problema

public class ConceptController implements Initializable {
    //...
	private void drag() {
        //...
		allbase.setOnMouseClicked(me ->  {
			try {
				YouTubeChannel youTubeChannel = getDataFor("andreplays15"); 	
                System.out.println("Canal:" + youTubeChannel.getChannelName());
                //...
			} catch (Exception exce) {
                //...
			}
		});		
	}
    //...
	public YouTubeChannel getDataFor(String channelId) throws IOException {
        //...
		List<Channel> channelsList = channelResult.getItems();
		if (channelsList.isEmpty()) {
			return null;
		}
        //...
	}
    //...
}

 

  • Vote 1

IRC : sim, é algo que ainda existe >> #p@p

Share this post


Link to post
Share on other sites
carlosguerradev
2 horas atrás, HappyHippyHippo disse:

Wet On Work ?

Já pus a funcionar obg =)

Share this post


Link to post
Share on other sites
JPTeixeira

Estou a começar a aprender Java, e também tive um problema semelhante, procurei no Stack Overflow e encontrei uma solução semelhante à sugerida pelo Hippo, no entanto aconselhavam a ter cuidado com este tipo de resolução porque pode "esconder" potenciais erros futuros do programa. Não percebi muito bem porquê, e em que casos é que é ou não aconselhável utilizar este tipo de approach por isso se me pudesses explicar ficaria agradecido @HappyHippyHippo

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.