Project 10: realtime database and FirebaseStorage data store and fetch data recyclerview


 



 step 1:-

ContentModel.java

package com.sandhya.youtube.models;

public class ContentModels {
String video_title,channel_name,views,date,id,type,publisher,description,video_url,video_tags,video;

public ContentModels() {
}

public ContentModels(String video_title, String channel_name, String views, String date, String id, String type, String publisher, String description, String video_url, String video_tags, String video) {
this.video_title = video_title;
this.channel_name = channel_name;
this.views = views;
this.date = date;
this.id = id;
this.type = type;
this.publisher = publisher;
this.description = description;
this.video_url = video_url;
this.video_tags = video_tags;
this.video = video;
}

public String getVideo_title() {
return video_title;
}

public void setVideo_title(String video_title) {
this.video_title = video_title;
}

public String getChannel_name() {
return channel_name;
}

public void setChannel_name(String channel_name) {
this.channel_name = channel_name;
}

public String getViews() {
return views;
}

public void setViews(String views) {
this.views = views;
}

public String getDate() {
return date;
}

public void setDate(String date) {
this.date = date;
}

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getType() {
return type;
}

public void setType(String type) {
this.type = type;
}

public String getPublisher() {
return publisher;
}

public void setPublisher(String publisher) {
this.publisher = publisher;
}

public String getDescription() {
return description;
}

public void setDescription(String description) {
this.description = description;
}

public String getVideo_url() {
return video_url;
}

public void setVideo_url() {
this.video_url = video_url;
}

public String getVideo_tags() {
return video_tags;
}

public void setVideo_tags(String video_tags) {
this.video_tags = video_tags;
}

public String getVideo() {
return video;
}

public void setVideo(String video) {
this.video = video;
}
}

 


step 1:-

ContentAdapter.java

package com.sandhya.youtube.adapter;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.google.android.exoplayer2.ExoPlayerFactory;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory;
import com.google.android.exoplayer2.extractor.ExtractorsFactory;
import com.google.android.exoplayer2.source.ExtractorMediaSource;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.trackselection.TrackSelector;
import com.google.android.exoplayer2.upstream.BandwidthMeter;
import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter;
import com.google.android.exoplayer2.upstream.DefaultHttpDataSourceFactory;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.sandhya.youtube.R;
import com.sandhya.youtube.activities.VideoViewActivity;
import com.sandhya.youtube.models.ContentModels;

import java.util.ArrayList;

import de.hdodenhof.circleimageview.CircleImageView;

public class ContentAdapter extends RecyclerView.Adapter<ContentAdapter.ViewHolder> {
Context context;
ArrayList<ContentModels> models;

DatabaseReference reference;
DatabaseReference databaseReference;
FirebaseUser user;
SimpleExoPlayer exoPlayer;

public ContentAdapter(Context context, ArrayList<ContentModels> models) {
this.context = context;
this.models = models;
}

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.video_item, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}

@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {

ContentModels model = models.get(position);
if (model != null) {
Glide.with(context).load(model.getVideo_url()).into(holder.imgThumb);
// Glide.with(context).load(model.getPublisher()).into(holder.imgProfile);
// holder.txtChannelName.setText(model.getChannel_name());
holder.txtView.setText(model.getViews());
holder.txtDate.setText(model.getDate());
holder.txtTitle.setText(model.getVideo_title());
setDate(model.getPublisher(),holder.imgProfile,holder.txtChannelName);
getVideoUrl();
}

holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(context, VideoViewActivity.class);
intent.putExtra("video",model.getVideo_url());
intent.putExtra("title",model.getVideo_title());
intent.putExtra("channel_name",model.getChannel_name());
intent.putExtra("profile",model.getPublisher());
intent.putExtra("date",model.getDate());
intent.putExtra("view",model.getViews());
context.startActivity(intent);
}
});
}



private void getVideoUrl() {
databaseReference = FirebaseDatabase.getInstance().getReference().child("Contents");
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
// this method is call to get the
// realtime updates in the data.
// this method is called when the
// data is changed in our Firebase console.
// below line is for getting the data
// from snapshot of our database.
String videoUrl = snapshot.child("video_url").getValue(String.class);
String title = snapshot.child("video_title").getValue(String.class);
// after getting the value for our video url
// we are passing that value to our
// initialize exoplayer method to load our video
initializeExoplayerView(videoUrl);
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
// calling on cancelled method when we receive
// any error or we are not able to get the data.
Toast.makeText(context, "Fail to get video url.", Toast.LENGTH_SHORT).show();
}
});

}
private void initializeExoplayerView(String videoUrl) {
try {
// bandwidthmeter is used for getting default bandwidth
BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
// track selector is used to navigate between video using a default seeker.
TrackSelector trackSelector = new DefaultTrackSelector(new AdaptiveTrackSelection.Factory(bandwidthMeter));

// we are adding our track selector to exoplayer.
exoPlayer = ExoPlayerFactory.newSimpleInstance(context, trackSelector);

// we are parsing a video url and
// parsing its video uri.
Uri videouri = Uri.parse(videoUrl);

// we are creating a variable for data source
// factory and setting its user agent as 'exoplayer_view'
DefaultHttpDataSourceFactory dataSourceFactory = new DefaultHttpDataSourceFactory("exoplayer_video");

// we are creating a variable for extractor
// factory and setting it to default extractor factory.
ExtractorsFactory extractorsFactory = new DefaultExtractorsFactory();

// we are creating a media source with above variables
// and passing our event handler as null,
MediaSource mediaSource = new ExtractorMediaSource(videouri, dataSourceFactory, extractorsFactory, null, null);

// inside our exoplayer view
// we are setting our player
// binding.idExoPlayerView.setPlayer(exoPlayer);

// we are preparing our exoplayer
// with media source.
exoPlayer.prepare(mediaSource);

// we are setting our exoplayer
// when it is ready.
exoPlayer.setPlayWhenReady(true);
} catch (Exception e) {
// below line is used for handling our errors.
Log.e("TAG", "Error : " + e.toString());
}

}



private void setDate(String publisher, CircleImageView imgProfile, TextView txtChannelName) {
reference = FirebaseDatabase.getInstance().getReference().child("Channels");
reference.child(publisher).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
String channelName = snapshot.child("Channel Name").getValue().toString();
String logo = snapshot.child("Profile_Picture").getValue().toString();
txtChannelName.setText(channelName);
Glide.with(context).load(logo).placeholder(R.drawable.ic_account).into(imgProfile);

}
}

@Override
public void onCancelled(@NonNull DatabaseError error) {

}
});
}

@Override
public int getItemCount() {
return models.size();
}

public class ViewHolder extends RecyclerView.ViewHolder {
ImageView imgThumb;
CircleImageView imgProfile;
TextView txtTitle, txtChannelName, txtView, txtDate;

public ViewHolder(@NonNull View itemView) {
super(itemView);

imgThumb = itemView.findViewById(R.id.imgThumb);
imgProfile = itemView.findViewById(R.id.imgProfile);
txtTitle = itemView.findViewById(R.id.txtTitle);
txtChannelName = itemView.findViewById(R.id.txtChannelName);
txtView = itemView.findViewById(R.id.txtView);
txtDate = itemView.findViewById(R.id.txtDate);
}
}
}

 step 1:-

fragment_home.xml

<?xml version="1.0" encoding="utf-8"?>
<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:orientation="vertical"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".fragements.HomeFragement">

<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/swiper">


<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/homeRecycler"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" />
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>


<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/homeProgressBar"
android:layout_centerInParent="true"
android:layout_gravity="center"/>



</RelativeLayout>

 step 1:-

HomeFragment.java

package com.sandhya.youtube.fragements;

import android.annotation.SuppressLint;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.sandhya.youtube.R;
import com.sandhya.youtube.adapter.ContentAdapter;
import com.sandhya.youtube.models.ContentModels;

import java.util.ArrayList;
import java.util.Collections;

public class HomeFragement extends Fragment {

public HomeFragement(){

}
SwipeRefreshLayout swipeRefreshLayout;
RecyclerView homeRecycler;
ArrayList<ContentModels> models;
ContentAdapter contentAdapter;
DatabaseReference reference;
ProgressBar homeProgressBar;
@SuppressLint("MissingInflatedId")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home_fragement, container, false);
homeRecycler = view.findViewById(R.id.homeRecycler);
homeRecycler.setHasFixedSize(true);
homeProgressBar = view.findViewById(R.id.homeProgressBar);
reference = FirebaseDatabase.getInstance().getReference().child("Contents");
getAllVideo();
swipeRefreshLayout = view.findViewById(R.id.swiper);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(false);
models = new ArrayList<>();
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if (snapshot.exists()){
homeProgressBar.setVisibility(View.GONE);
models.clear();
for ( DataSnapshot dataSnapshot : snapshot.getChildren()){
ContentModels model = dataSnapshot.getValue(ContentModels.class);
models.add(model);
}
//shu
Collections.shuffle(models);
contentAdapter = new ContentAdapter(getActivity(),models);
homeRecycler.setAdapter(contentAdapter);
contentAdapter.notifyDataSetChanged();
}else {
homeProgressBar.setVisibility(View.VISIBLE);
Toast.makeText(getActivity(), "No data found", Toast.LENGTH_SHORT).show();
}
}

@Override
public void onCancelled(@NonNull DatabaseError error) {
Toast.makeText(getActivity(), ""+error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
});

getSwipRefresh();
return view;
}

private void getSwipRefresh() {

}

public void getAllVideo(){

models = new ArrayList<>();
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if (snapshot.exists()){
homeProgressBar.setVisibility(View.GONE);
models.clear();
for ( DataSnapshot dataSnapshot : snapshot.getChildren()){
ContentModels model = dataSnapshot.getValue(ContentModels.class);
models.add(model);
}
//shu
Collections.shuffle(models);
contentAdapter = new ContentAdapter(getActivity(),models);
homeRecycler.setAdapter(contentAdapter);
contentAdapter.notifyDataSetChanged();
}else {
homeProgressBar.setVisibility(View.VISIBLE);
Toast.makeText(getActivity(), "No data found", Toast.LENGTH_SHORT).show();
}
}

@Override
public void onCancelled(@NonNull DatabaseError error) {
Toast.makeText(getActivity(), ""+error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}

 step 1:-

activity_publish.xml

<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context=".activities.PublishActivity">

<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">

<de.hdodenhof.circleimageview.CircleImageView
android:id="@+id/imgProfile"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="10dp"
android:layout_marginBottom="10dp"
android:src="@drawable/ic_account" />

<Button
android:id="@+id/btnUpload"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_margin="10dp"
android:text="upload" />
</RelativeLayout>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:orientation="vertical">

<VideoView
android:id="@+id/videoView"
android:layout_width="match_parent"
android:layout_height="220dp" />
</LinearLayout>

<EditText
android:id="@+id/edtTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_marginTop="5dp"
android:background="@drawable/edtbg"
android:hint="Title"
android:imeOptions="actionNext"
android:padding="10dp" />

<EditText
android:id="@+id/edtDescription"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_marginTop="5dp"
android:autoLink="all|email|map|phone|web|none"
android:background="@drawable/edtbg"
android:gravity="start"
android:hint="Description"
android:imeOptions="actionNext"
android:minHeight="150dp"
android:padding="10dp"
android:textColor="@color/black"
android:textColorLink="@color/purple_500" />

<com.hootsuite.nachos.NachoTextView
android:id="@+id/nachoTag"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_marginTop="5dp"
android:background="@drawable/edtbg"
android:hint="Tags"
android:imeOptions="actionNext"
android:padding="7dp" />

<TextView
android:id="@+id/txtChoosePlaylist"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center"
android:text="Choose Playlist"
android:textColor="@color/purple_500"
android:textSize="16dp"
android:textStyle="bold" />

<ProgressBar
android:id="@+id/progressbar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginEnd="20dp"
android:padding="5dp" />

<TextView
android:id="@+id/txtProgress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="progress"
android:textSize="16dp"
android:textStyle="bold" />


</LinearLayout>
</androidx.core.widget.NestedScrollView>

</RelativeLayout>

 step 1:-

PublishActivitry.java

package com.sandhya.youtube.activities;

import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.hootsuite.nachos.terminator.ChipTerminatorHandler;
import com.sandhya.youtube.R;
import com.sandhya.youtube.databinding.ActivityPublishBinding;

import java.text.DateFormat;
import java.util.Date;
import java.util.HashMap;

public class PublishActivity extends AppCompatActivity {
ActivityPublishBinding binding;
private static final int PICK_GALLERY = 102;
String type;
Uri videoUri;
String videoUrl;
MediaController controller;

FirebaseUser user;
DatabaseReference reference;
int videosCount;
StorageReference storageReference;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityPublishBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());

initPlaylist();

initVideoUpload();

user = FirebaseAuth.getInstance().getCurrentUser();
reference = FirebaseDatabase.getInstance().getReference().child("Contents");
storageReference = FirebaseStorage.getInstance().getReference().child("Contents");

binding.nachoTag.addChipTerminator(',', ChipTerminatorHandler.BEHAVIOR_CHIPIFY_ALL);

binding.videoView.findViewById(R.id.videoView);
controller = new MediaController(this);
controller.setBackground(new ColorDrawable(Color.TRANSPARENT));
Intent intent = getIntent();
if (intent != null) {
videoUri = intent.getData();
binding.videoView.setVideoURI(videoUri);
binding.videoView.setMediaController(controller);
binding.videoView.pause();
// binding.videoView.start();
}

}

public void initVideoUpload() {
binding.btnUpload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String title = binding.edtTitle.getText().toString();
String description = binding.edtDescription.getText().toString();
String tags = binding.nachoTag.getAllChips().toString().replace(",", "");

if (title.isEmpty() || description.isEmpty() || tags.isEmpty()) {
Toast.makeText(PublishActivity.this, "fill all fields.", Toast.LENGTH_SHORT).show();
} else {
uploadVideoToStorage(title, description, tags);
}
}
});
}

private void uploadVideoToStorage(String title, String description, String tags) {

final StorageReference sRef = storageReference.child(user.getEmail()).child
(System.currentTimeMillis() + "," + getFileExtension(videoUri));
sRef.putFile(videoUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
sRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
videoUrl = uri.toString();
//save data firebase
saveDataToFirebase(title, description, tags, videoUrl);
}
});
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
@Override
public void onProgress(@NonNull UploadTask.TaskSnapshot snapshot) {
double progress = 100.0 * snapshot.getBytesTransferred() / snapshot.getTotalByteCount();
binding.progressbar.setProgress((int) progress);
binding.txtProgress.setText("Uploading: " + (int) progress + "%");
}
});
}

private void saveDataToFirebase(String title, String description, String tags, String videoUrl) {
String currentDate = DateFormat.getDateInstance().format(new Date());
String currentTime = DateFormat.getTimeInstance().format(new Date());
String Id = reference.push().getKey();
HashMap<String, Object> map = new HashMap<>();
map.put("ID", Id);
map.put("video_title", title);
map.put("video_des", description);
map.put("video_tag", tags);
map.put("video_url", videoUrl);
map.put("publisher", user.getUid());
map.put("type","video");
map.put("view",0);
map.put("date", currentDate);
map.put("time", currentTime);
reference.child(Id).setValue(map).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {


binding.progressbar.setVisibility(View.GONE);
Toast.makeText(PublishActivity.this, "Video Uploaded", Toast.LENGTH_SHORT).show();
startActivity(new Intent(PublishActivity.this, MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK));
finish();
updateCount();
} else {
binding.progressbar.setVisibility(View.GONE);
Toast.makeText(PublishActivity.this, "Failed to upload" + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}

private void updateCount() {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Playlists");
int update = videosCount + 1;
HashMap<String, Object> map = new HashMap<>();
map.put("videos", update);
reference.child(user.getUid()).updateChildren(map);
}

private String getFileExtension(Uri uri) {
ContentResolver resolver = getContentResolver();
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
return mimeTypeMap.getExtensionFromMimeType(resolver.getType(uri));

}

public void initPlaylist() {
binding.txtChoosePlaylist.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
BottomSheetDialog dialog = new BottomSheetDialog(PublishActivity.this);
dialog.setContentView(R.layout.playlist_dialog_item);
dialog.setCancelable(true);
dialog.setCanceledOnTouchOutside(true);
dialog.show();

EditText edtPlayList = dialog.findViewById(R.id.edtPlaylist);

// models.add(new PlaylistModel("Nadasdf","23456","1"));
// models.add(new PlaylistModel("Nadasdf","2345xss6","1"));
// models.add(new PlaylistModel("Nadasdf","23sd456","1"));
// models.add(new PlaylistModel("Nadasdf","2aef3456","1"));
// models.add(new PlaylistModel("Nadasdf","asd","1"));
// models.add(new PlaylistModel("Nadasdf","23asd456","1"));
// models.add(new PlaylistModel("Nadasdf","e","23"));

// models = new ArrayList<>();
// adapter = new PlaylistAdapter(PublishActivity.this,models);
// playlistRecycler = dialog.findViewById(R.id.playlistRecycler);
// playlistRecycler.setLayoutManager(new LinearLayoutManager(PublishActivity.this));
// FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
// DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Playlists");
// reference.child(user.getUid()).addValueEventListener(new ValueEventListener() {
// @Override
// public void onDataChange(@NonNull DataSnapshot snapshot) {
// if (snapshot.exists()) {
// for (DataSnapshot snapshot1 : snapshot.getChildren()) {
// PlaylistModel model = snapshot1.getValue(PlaylistModel.class);
// models.add(model);
// }
// playlistRecycler.setAdapter(adapter);
// adapter.notifyDataSetChanged();
// if (models.isEmpty()){
//
// }else {
//
// }
// }
// }
//
// @Override
// public void onCancelled(@NonNull DatabaseError error) {
//
// Toast.makeText(PublishActivity.this, error.getMessage(), Toast.LENGTH_LONG).show();
// Log.e("Error", error.getMessage());
// }
// });

ProgressDialog progressDialog = new ProgressDialog(PublishActivity.this);
progressDialog.setTitle("New Playlist Create...");
progressDialog.setCancelable(true);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setMessage("Creating...");

Button btnAddPlaylist = dialog.findViewById(R.id.btnAddPlaylist);
btnAddPlaylist.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
progressDialog.show();
String newplaylist = edtPlayList.getText().toString();
if (newplaylist.isEmpty()) {
Toast.makeText(PublishActivity.this, "Enter Playlist Name", Toast.LENGTH_SHORT).show();
} else {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Playlists");
HashMap<String, Object> map = new HashMap<>();
map.put("playlist", newplaylist);
map.put("Email", user.getEmail());
map.put("video", videoUrl);
map.put("uid", user.getUid());
reference.child(user.getUid()).child(newplaylist).setValue(map).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
progressDialog.dismiss();
dialog.dismiss();
Toast.makeText(PublishActivity.this, newplaylist + " New Playlist Created!", Toast.LENGTH_SHORT).show();
} else {
progressDialog.dismiss();
dialog.dismiss();
Toast.makeText(PublishActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}

}
});


}
});
}

public void checkUserPlaylistAlready(RecyclerView playlistRecycler) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Playlists");
reference.child(user.getUid()).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
playlistRecycler.setVisibility(View.VISIBLE);

} else {
playlistRecycler.setVisibility(View.GONE);
}
}

@Override
public void onCancelled(@NonNull DatabaseError error) {

}
});
}

public void initVideoView() {
binding.videoView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
BottomSheetDialog dialog = new BottomSheetDialog(PublishActivity.this);
dialog.setContentView(R.layout.camera_gallery_item);
dialog.setCancelable(false);
dialog.setCanceledOnTouchOutside(true);
dialog.show();

LinearLayout llGallery, llCamera;
llCamera = dialog.findViewById(R.id.llCamera);
llGallery = dialog.findViewById(R.id.llGallery);

llGallery.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent iGallery = new Intent(Intent.ACTION_GET_CONTENT);
iGallery.setType("video/*");
startActivityForResult(Intent.createChooser(iGallery, "Select video"), PICK_GALLERY);
}
});
}
});
}
}

إرسال تعليق

Post a Comment (0)

أحدث أقدم