Click here to Skip to main content
15,867,308 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm building an app and I'm stuck on youtube part.I need a solution on how to open a youtube video by clicking on a item of listview.I'm using Fragments and I already retrieved data from Firebase.Those data are Albums and tracks of said albums.When you click on any album, it opens a new Activity with tracks.Now, I want when user clicks on any of tracks, to open a video of that track. I need simplest code, nothing too complicated.I'll post my code.I hope you guys and girls can help my, cause I'm doing this for the first time and I really need some help.Thank you in advance.

public class TracksActivity extends FragmentActivity implements ValueEventListener {


    public static final String TRACKS = "Tracks";
    public static final String DB_NAME = "MetalApp";
    public static final String ALBUM_KEY = "SelectedAlbumKey";
    public static final String LOG_TAG = "FB_database_tag";


    private int targetPosition = -1;

    private DatabaseReference mDatabaseReference;
    private TrackAdapter tAdapter;
    @BindView(R.id.lvTracks)
    ListView lvTracks;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.track_fragment);
        ButterKnife.bind(this);

    }

    @Override
    public View onCreateView(String name, Context context, AttributeSet attrs) {
        Intent podaci = getIntent();
        targetPosition = podaci.getIntExtra(ALBUM_KEY, -1);
        this.mDatabaseReference = FirebaseDatabase.getInstance().getReference(DB_NAME).child(TRACKS);
        this.mDatabaseReference.addValueEventListener(this);

        return super.onCreateView(name, context, attrs);
    }

    @Override
    public void onDataChange(DataSnapshot s) {
        final List<Track> tracskList = new ArrayList<>();
        HashMap<String, HashMap> tracksInDatabase = (HashMap<String, HashMap>) s.getValue();

        Set<String> keys = tracksInDatabase.keySet();
        List<String> tempKeys = new ArrayList<>();
        tempKeys.addAll(keys);
        Collections.sort(tempKeys, new Comparator<String>() {
            @Override
            public int compare(String s, String t1) {
                return s.compareToIgnoreCase(t1);

            }

        });

        int currentPosition = 0;
        for (String albumTrack : tempKeys) {
            if (currentPosition == targetPosition) {
                HashMap<String, HashMap> trackList = tracksInDatabase.get(albumTrack);
                List<Track> tracks = mapTracks(trackList);
                Collections.sort(tracks, new Comparator<Track>() {
                    @Override
                    public int compare(Track track, Track t1) {
                        return track.getId().compareTo(t1.getId());
                    }
                });
                tAdapter = new TrackAdapter(tracks);
                this.lvTracks.setAdapter(tAdapter);

            }

            currentPosition++;
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

        Log.e(LOG_TAG, databaseError.getMessage());

    }

    private List<Track> mapTracks(HashMap<String, HashMap> m) {
        List<Track> r = new ArrayList<>();
        Set<String> keys = m.keySet();
        for (String key : keys) {
            HashMap<String, Object> album = m.get(key);
            String id = (String) album.get("id");
            String title = (String) album.get("title");
            String url = (String) album.get("url");
            Track t = new Track(id, title, url);
            r.add(t);
        }

        return r;

    }

    @OnItemClick(R.id.lvTracks)
    public void onItemClick(int position){
        String[] arrayList = this.getResources().getStringArray(R.array.tracks);
        String tr = arrayList[position];
        Uri uri = Uri.parse(tr);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        this.startActivity(intent);
        
    }
    
}


Method onItemClick is probably wrong, so I would ask you to help me with that.

This is Activity that should contain code for youtube. Also, my xml. is fragment.

public class YT_Activity extends AppCompatActivity  {

    @BindView(R.id.f_Youtube)
    Fragment f_Yotube;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_yt_);
        ButterKnife.bind(this);

    }
}


What I have tried:

I tryied using google to find answer, but I didn't find what I was looking for.Same thing on Youtube.
Posted
Comments
David Crow 26-Dec-17 14:28pm    
"Now, I want when user clicks on any of tracks, to open a video of that track."

Where is the video located?
Member 13593129 27-Dec-17 11:17am    
All my data are on Firebase, including url of every video.
David Crow 27-Dec-17 11:21am    
Okay, so in response to a ListView click, can you have something like:
public static void watchYoutubeVideo(Context context, String id)
{    
    Intent appIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube:" + id));    
    Intent webIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com/watch?v=" + id));

    try     
    {        
        context.startActivity(appIntent);    
    }     
    catch (ActivityNotFoundException ex)     
    {        
        context.startActivity(webIntent);    
    }
}
That way it will fallback to viewing in a browser if YouTube app is not available.
Member 13593129 27-Dec-17 14:01pm    
So, you say that I should put this method instead of my method onItemClick? I did that, and nothing is happening.When I click on track, and youtube doeesn' t open. I found an example of Youtube_Activity code. It looks like this:

public class Youtube_class extends YouTubePlayerSupportFragment {


private static final String currentVideoID = "id";
private YouTubePlayer yPlayer;
@BindView(R.id.frame_layout) FrameLayout frame_Layout;

@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
View view = inflater.inflate(R.layout.activity_yt_,container, false);



return view;
}

public static Youtube_class newInstance(String url) {

Youtube_class youtube_activity = new Youtube_class();

Bundle bundle = new Bundle();
bundle.putString("url", url);
youtube_activity.setArguments(bundle);
youtube_activity.init();


return youtube_activity;

}


private void init() {

initialize(Youtube_key.getAPI_KEY(), new YouTubePlayer.OnInitializedListener() {

@Override
public void onInitializationFailure(YouTubePlayer.Provider arg0, YouTubeInitializationResult arg1) {
}

@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) {
yPlayer = player;
yPlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);

if (!wasRestored) {
yPlayer.loadVideo(getArguments().getString("url"), 0);

Youtube_class myFragment = Youtube_class.newInstance("video_id");
getFragmentManager().beginTransaction().replace(R.id.frame_layout, myFragment).commit();

}

}

});
}
/* public void onYouTubeVideoPaused() {
yPlayer.pause();


}*/

}

David Crow 27-Dec-17 14:07pm    
"So, you say that I should put this method instead of my method onItemClick?"

Of course not. onItemClick() is required to respond to an item click. In it, you can call the function I suggested, or take the code from it and put in your onItemClick() directly.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900