chapter data

 package com.rscit.rscitapp.act.Chapter;


import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Toast;

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

import com.bumptech.glide.Glide;
import com.google.android.material.snackbar.Snackbar;
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.firestore.FirebaseFirestore;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.rscit.rscitapp.adapter.Oadapter;
import com.rscit.rscitapp.databinding.ActivityAddChapterBinding;
import com.rscit.rscitapp.model.NotesData;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

public class AddChapter extends AppCompatActivity {



// Replace this line
private DatabaseReference databaseReference;
private FirebaseFirestore db;

private ActivityAddChapterBinding binding;
private static final int PICK_IMAGE_REQUEST = 1;
private Uri imageUri; // Variable to store the image URI

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityAddChapterBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
db = FirebaseFirestore.getInstance();

databaseReference = FirebaseDatabase.getInstance().getReference();
Objects.requireNonNull(getSupportActionBar()).setTitle("Add chapter");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
binding.postit.setOnClickListener(view -> {
String chapterName = binding.chapterName.getText().toString();
String videoUrl = binding.videoUrl.getText().toString();
String description = binding.description.getText().toString();

// Save text data first, then upload the image
saveData(chapterName, description,videoUrl );
});
setupChapterList();
fetchChapter();

binding.selectImage.setOnClickListener(view -> openFileChooser());
}

private void setupChapterList() {
binding.chapterList.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));

// Assume you have a list of chapter names, replace this with your data
List<String> chapterNames = Arrays.asList("Chapter 1", "Chapter 2", "Chapter 3");

Oadapter adapter = new Oadapter(chapterNames);
binding.chapterList.setAdapter(adapter);

// Add this method to handle item click
adapter.setOnItemClickListener(selectedChapter -> {
// Set the selected chapter name in the chapterName EditText
binding.chapterName.setText(selectedChapter);
// binding.videoUrl.setText(adapte);
});
}

private void openFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
imageUri = data.getData();
binding.selectImage.setImageURI(imageUri);
}
}

private void fetchChapterData(String chapterName) {
DatabaseReference chapterDataRef = databaseReference.child("Rscit").child("Chapter").child(chapterName);

chapterDataRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
// Assuming your data model class is NotesData, replace it with your actual class
NotesData chapterData = dataSnapshot.getValue(NotesData.class);
if (chapterData != null) {
// Set data for the selected chapter
binding.description.setText(chapterData.getDescription());
binding.videoUrl.setText(chapterData.getVideoUrl());
binding.chapterName.setText(chapterData.getChapterName());
// You may need to load the image here using Glide or another image loading library
Glide.with(AddChapter.this).load(chapterData.getImageurl()).into(binding.selectImage);
}
}
}

@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Toast.makeText(AddChapter.this, "Failed to fetch chapter data: " + databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void fetchChapter() {
DatabaseReference chapterRef = databaseReference.child("Rscit").child("Chapter");

chapterRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
List<String> chapterNames = new ArrayList<>();

for (DataSnapshot chapterSnapshot : dataSnapshot.getChildren()) {
String chapterName = chapterSnapshot.getKey();
chapterNames.add(chapterName);
}

// Update the RecyclerView with the retrieved chapter names
updateChapterList(chapterNames);
}
}

@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Toast.makeText(AddChapter.this, "Failed to fetch chapter names: " + databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}

private void updateChapterList(List<String> chapterNames) {
Oadapter adapter = new Oadapter(chapterNames);
binding.chapterList.setAdapter(adapter);

// Add this method to handle item click
// Set the selected chapter name in the chapterName EditText
adapter.setOnItemClickListener(this::fetchChapterData);
}

private void saveData(String chapterName, String description, String videoUrl) {
if (TextUtils.isEmpty(chapterName) || TextUtils.isEmpty(description) || TextUtils.isEmpty(videoUrl)) {
// Show Snackbar indicating that all fields are compulsory
Snackbar.make(binding.getRoot(), "All fields are compulsory", Snackbar.LENGTH_SHORT).show();
return;
}

if (imageUri == null) {
saveTextData(chapterName, description, videoUrl, "");
} else {
uploadImage(chapterName, description, videoUrl);
}
}


@SuppressLint("SetTextI18n")
private void saveTextData(String chapterName,String description,String imageUrl, String videoUrl ) {
NotesData notesData = new NotesData(chapterName,description,imageUrl,videoUrl);
DatabaseReference textDataRef = databaseReference.child("Rscit").child("Chapter").child(chapterName);
textDataRef.setValue(notesData)
.addOnSuccessListener(unused -> {
Objects.requireNonNull(binding.chapterName.getText()).clear();
Objects.requireNonNull(binding.videoUrl.getText()).clear();
Objects.requireNonNull(binding.description.getText()).clear();
binding.error.setText("Data posted successfully");
})
.addOnFailureListener(e -> {
Toast.makeText(AddChapter.this, "Failed to save text data to database: " + e.getMessage(), Toast.LENGTH_SHORT).show();
});
}
@SuppressLint("SetTextI18n")
private void uploadImage(String chapterName, String description,String videoUrl) {
StorageReference storageRef = FirebaseStorage.getInstance().getReference();
StorageReference fileReference = storageRef.child(chapterName);


fileReference.putFile(imageUri)
.addOnSuccessListener(taskSnapshot -> fileReference.getDownloadUrl().addOnSuccessListener(uri -> {
// Image uploaded successfully, update the text data node with the image URL
saveTextData(chapterName, description,videoUrl, uri.toString());
}).addOnFailureListener(e -> {
Toast.makeText(AddChapter.this, "Failed to get image download URL: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}))
.addOnFailureListener(e -> {
// Handle errors during the image upload
Toast.makeText(AddChapter.this, "Failed to upload image: " + e.getMessage(), Toast.LENGTH_SHORT).show();
});
}@Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
}

Comments