Is it possible to "Archive" Firebase records - java

I currently have an Android ListView which displays data from my Firebase database. When I click on a data record in my ListView an Alert Dialog appears with and Archive Button.
I want a selected record to be transferred to another ListView in another activity within my application, i.e. "archived".
I know this will mean creating an archive node for my Firebase database.
Below is the method for bring up my Alert Dialog, which includes a Button to carry out my method archiveMaintenance. I'm stuck however, as to where to start on what to put in archiveMaintenance.
showProgressDialog
private void showProgressDialog(final String id, String title, String description, String property, String maintenanceTitle) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.archive_maintenance, null);
dialogBuilder.setView(dialogView);
final Spinner spinnerProgress = (Spinner) dialogView.findViewById(R.id.spinnerProgress);
final Button buttonUpdateProgress = (Button) dialogView.findViewById(R.id.buttonUpdateProgress);
dialogBuilder.setTitle("Maintenance: " + maintenanceTitle);
final AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
buttonUpdateProgress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String title = editTextTitle.getText().toString().trim();
String desc = editTextDesc.getText().toString().trim();
String progress = spinnerProgress.getSelectedItem().toString();
String property = spinnerProperty.getSelectedItem().toString();
updateProgress(title, desc, id, property, progress);
alertDialog.dismiss();
}
});
buttonUpdateArchive.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
archiveMaintenance(id);
}
});
}
archivedMaintenance
private void archiveMaintenance(String id) {
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference recordsRef = rootRef.child("maintenance");
DatabaseReference recordIdRef = recordsRef.child(id);
DatabaseReference archivedRecordsRef = rootRef.child("archive");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
MaintenanceList maintenanceList = dataSnapshot.getValue(MaintenanceList.class); //First step
archivedRecordsRef.child(id).setValue(maintenanceList); //Second step
dataSnapshot.getRef().removeValue(); //Third step
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
recordIdRef.addListenerForSingleValueEvent(valueEventListener);
}
MaintenanceList
public class MaintenanceList extends ArrayAdapter<Maintenance> {
private Activity context;
private List<Maintenance> maintenanceList;
public MaintenanceList(Activity context, List<Maintenance> maintenanceList) {
super(context, R.layout.maintenance_list_layout, maintenanceList);
this.context = context;
this.maintenanceList = maintenanceList;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.maintenance_list_layout, null, true);
TextView textViewTitle = (TextView) listViewItem.findViewById(R.id.textViewTitle);
TextView textViewDesc = (TextView) listViewItem.findViewById(R.id.textViewDesc);
TextView textViewProperty = (TextView) listViewItem.findViewById(R.id.textViewProperty);
TextView textViewProgress = (TextView) listViewItem.findViewById(R.id.textViewProgress);
Maintenance maintenance = maintenanceList.get(position);
textViewTitle.setText(maintenance.getMaintenanceTitle());
textViewDesc.setText(maintenance.getMaintenanceDescription());
textViewProperty.setText(maintenance.getMaintenanceProperty());
textViewProgress.setText(maintenance.getMaintenanceProgress());
return listViewItem;
}
}
I have created and activity with a ListView ready to take the data - ArchiveList.
Any thoughts/pointers on this would be much appreciated.

In the archiveMaintenance(id) method you need to add code that will help you move the record from a location to another. Let's assume you have a records node in which exist all your records and a archivedRecords node where exist all archived records. Assuming aso that you have a helper class that is named RecordModel, to move a record from a location to another, you need to follow the next steps:
get the record
add the record to new location
remove the record from the old location
Your method should look like this:
private void archiveMaintenance(String recordId) {
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference recordsRef = rootRef.child("records");
DatabaseReference recordIdRef = recordsRef.child(recordId);
DatabaseReference archivedRecordsRef = rootRef.child("archivedRecords");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
RecordModel recordModel = dataSnapshot.getValue(RecordModel.class); //First step
archivedRecordsRef.child(recordId).setValue(recordModel); //Second step
dataSnapshot.getRef().removeValue(); //Third step
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
recordIdRef.addListenerForSingleValueEvent(valueEventListener);
}

Related

How do i set ImageView,TextViews of an activity by retriving Image,TextViews that i uploaded to firebase database or storage?

I am creating a new android application that retrieves one image,two texts that have been uploaded to firebase using different or say admin app,and the uploaded image and text views will be retrieved into one single card view as shown in image. which is in a recyclerview,now,i want it to be like any other blog app.So that when the user click on that card view,the imageview,the heading,the matter all these views will be arranged in a default layout as shown in image below.I mean like setting the image view to the image been retrieved from firebase and both text views to the texts retrieved from firebase.So that when ever any user clicks any blog post that retrieved from firebase,it should open that default layout and all the views will go to their places declared.how can i achieve this?. The code that i used to retrieve and show the content in a cardview is as below.As i am new to stackoverflow,i dont have enough reputation to add images.please go through the image links below.
image one
https://ibb.co/kJtvNTm
https://ibb.co/KXB8fdj
This is for my own educational purpose,i am new in developing android applications and firebase.I tried retrieving them but it doesn't do will to put them in their place
PostRecyclerActivity.java
private RecyclerView mRecyclerView;
private PostImageAdapter mAdapter;
private ProgressBar mProgressCircle;
private DatabaseReference mDatabaseRef;
private List<PostUpload> mUploads;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.post_image_recycler);
mRecyclerView = findViewById(R.id.post_recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mProgressCircle = findViewById(R.id.post_progress_circle);
mUploads = new ArrayList<>();
mDatabaseRef = FirebaseDatabase.getInstance().getReference("posts");
mDatabaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
PostUpload upload = postSnapshot.getValue(PostUpload.class);
mUploads.add(upload);
}
mAdapter = new PostImageAdapter(PostImageRecyclerActivity.this, mUploads);
mRecyclerView.setAdapter(mAdapter);
mProgressCircle.setVisibility(View.INVISIBLE);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(PostImageRecyclerActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
mProgressCircle.setVisibility(View.INVISIBLE);
}
});
}
}
PostImageAdapter.java
public class PostImageAdapter extends RecyclerView.Adapter<PostImageAdapter.ImageViewHolder> {
private Context mContext;
private List<PostUpload> mUploads;
public PostImageAdapter(Context context, List<PostUpload> uploads) {
mContext = context;
mUploads = uploads;
}
#Override
public ImageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.post_card, parent, false);
return new ImageViewHolder(v);
}
#Override
public void onBindViewHolder(ImageViewHolder holder, int position) {
PostUpload uploadCurrent = mUploads.get(position);
holder.textViewName.setText(uploadCurrent.getHeading());
Picasso.get()
.load(uploadCurrent.getmImageUrl())
.fit()
.centerCrop()
.into(holder.imageView);
}
#Override
public int getItemCount() {
return mUploads.size();
}
public class ImageViewHolder extends RecyclerView.ViewHolder {
public TextView textViewName;
public ImageView imageView;
public ImageViewHolder(View itemView) {
super(itemView);
textViewName = itemView.findViewById(R.id.text_view_name);
imageView = itemView.findViewById(R.id.post_image_view_upload);
}
}
}
PostUpload.java
public class PostUpload {
private String mHeading;
private String mMatter;
private String mImageUrl;
public PostUpload() {
}
public PostUpload(String heading, String matter, String imageUrl) {
if (heading.trim().equals("")) {
heading = "No Name";
}
mHeading = heading;
mMatter = matter;
mImageUrl = imageUrl;
}
public String getHeading(){
return mHeading;
}
public void setHeading(String name){
mHeading=name;
}
public String getMatter(){
return mMatter;
}
public void setMatter(String name){
mMatter=name;
}
public String getmImageUrl(){
return mImageUrl;
}
public void setImageUrl(String imageUrl){
mImageUrl=imageUrl;
}
}
I expect the output after clicking the blog-post should be having the image and heading set in their places as shown in image two and and a matter is retrieved from firebase and set into the other text view as shown in image two.
When you are getting the data from Firebase, you are storing it at your mUploads array of type PostUpload the data that you want to show into those CardViews
Here
mDatabaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
PostUpload upload = postSnapshot.getValue(PostUpload.class);
mUploads.add(upload);
}
mAdapter = new PostImageAdapter(PostImageRecyclerActivity.this, mUploads);
mRecyclerView.setAdapter(mAdapter);
mProgressCircle.setVisibility(View.INVISIBLE);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(PostImageRecyclerActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
mProgressCircle.setVisibility(View.INVISIBLE);
}
});
When you hit mRecyclerView.setAdapter(mAdapter); you already have filled the array and show the info to the user.
After that you can use the getItem() from the adapter.
You just need to override that method inside your PostImageAdapter
public PostUpload getItem(int position) {
return mUploads.get(position);
}
Once you have this method, you can access any item from the array filled from Firebase in your PostRecyclerActivity.java
So, after you click an item in your RecyclerView, you can get the position and get the object info from that position
Here are many good ways to implement the click of each row of the recyclerview (I recommend the first one)
So, after you implement the click of each row in your recyclerview, just pass that data throught a bundle or extras to the other Activity
Pseudo code Example
recyclerView.onClick{...
public void recyclerViewListClicked(View v, int position){
if(mAdapter.getItemCount() > 0){
PostUpload post = mAdapter.getItem(position);
}else{
Toast("There is no data into the element");
}
//Go to another Activity
Intent intent = new Intent(PostRecyclerActivity.this,yourSecondActivity.class);
intent.putExtra(post.getHeadding,"postheading");
intent.putExtra(post.getMatter,"postmatter");
//You keep doing the same with the other data you need to send out.
startActivity(intent);
}
How to get the data from Activity2
Intent intent = getIntent();
String postheading = intent.getStringExtra("postheading");
String postmatter = intent.getStringExtra("postmatter");
Since the image is an URL of type String, just pass it as intent.putExtra() as we did before and you can get that URL from the other Activity and inflate your image.

How to remove one item on my data base when I click on my "delete" button?

I'm new to android studio, and for my android application I'm use Firebase.
I want to remove one item from my database when I click on my button delete(btnDelete).
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
Query query= FirebaseDatabase.getInstance()
.getReference().child("users").child(uid).child("foto");
public ViewHolder(#NonNull View itemView) {
super(itemView);
foto_root=itemView.findViewById(R.id.foto_root);
tvNameF=itemView.findViewById(R.id.tvNameF);
tvPhoneF=itemView.findViewById(R.id.tvPhoneF);
tvAdressF=itemView.findViewById(R.id.tvAdressF);
tvMailF=itemView.findViewById(R.id.tvMailF);
tvNoteF=itemView.findViewById(R.id.tvNoteF);
btnDelete=itemView.findViewById(R.id.btnDelete);
}
public void setTvNameF(String tvNameFs){
tvNameF.setText(tvNameFs);
}
public void setTvPhoneF(String tvPhoneFs){
tvPhoneF.setText(tvPhoneFs);
}
}
/*
get on dataBase
*/
private void fetch() {
FirebaseRecyclerOptions<Foto> options=
new FirebaseRecyclerOptions.Builder<Foto>().setQuery(query, snapshot -> new Foto(
snapshot.child("id").getKey(),
snapshot.child("name").getValue().toString(),
snapshot.child("phone").getValue().toString(),
snapshot.child("adress").getValue().toString(),
snapshot.child("email").getValue().toString(),
snapshot.child("note").getValue().toString())).build();
adapter = new FirebaseRecyclerAdapter<Foto, FotoActivity.ViewHolder>(options) {
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.foto_item,parent,false);
return new ViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull ViewHolder viewHolder, int i, #NonNull Foto foto) {
viewHolder.setTvNameF(foto.getNameF());
viewHolder.setTvPhoneF(foto.getPhoneF());
viewHolder.setTvAdressF(foto.getAdressF());
viewHolder.setTvMailF(foto.getEmailF());
viewHolder.setTvNoteF(foto.getNoteF());
viewHolder.btnDelete.setOnClickListener(v -> {
delete();
});
}
};
rvFoto.setAdapter(adapter);
}
private void delete() {
Toast.makeText(FotoActivity.this, "remove", Toast.LENGTH_SHORT).show();
}
private void viewRecyclerViewFoto() {
linearLayoutManager=new LinearLayoutManager(this);
rvFoto.setLayoutManager(linearLayoutManager);
rvFoto.setHasFixedSize(true);
}
}
// adapter class
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
private void setInfoFoto() {
DatabaseReference databaseReference=
FirebaseDatabase.getInstance().getReference().child("users").child(uid).child("foto").push();
Map<String,Object> mapFoto=new HashMap<>();
mapFoto.put("id",databaseReference.getKey());
mapFoto.put("name",etNameF.getText().toString());
mapFoto.put("phone",etPhoneF.getText().toString());
mapFoto.put("adress",etAdressF.getText().toString());
mapFoto.put("email",etMailF.getText().toString());
mapFoto.put("note",etNoteF.getText().toString());
databaseReference.setValue(mapFoto);
}
I want remove one item from foto and not all database.
Just use the following in your delete function, this will delete the value of "phone" node. You will need to know the uid of the user you want to delete otherwise you can replace it with a database node reference but then that will delete phone from all the user ids. Basically you will listen to the foto node, get all the push ids and loop through the push ids to remove the desired node.
Declare The Variables
private static final String TAG = "TestActivity";
private DatabaseReference fbDbRef;
OnCreate
final String uid = "youruid";
fbDbRef = FirebaseDatabase.getInstance().getReference().child("users")
.child(uid).child("foto");
Your Function
private void delete() {
fbDbRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
final String pushKey = snapshot.getKey();
Log.d(TAG, "pushKey: " + pushKey);
fbDbRef.child(pushKey).child("phone").removeValue();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}

Data fetched from sqlite not showing in recyclerview

messageList = (RecyclerView) findViewById(R.id.message_list);
mRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
linearLayoutManager = new LinearLayoutManager(getApplicationContext());
messageList.setLayoutManager(linearLayoutManager);
mAdapter = new MessagesAdapter(messages);
messageList.setAdapter(mAdapter);
final MainData mHelper = new MainData(this);
final Cursor csr = mHelper.getAllQuestions3();
sqlite = mDatabaseReference.child("Messages").child(MessageSenderId).child(MessageRecieverId);
valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
//I add the data from firebase to SQLITE here
while (csr.moveToNext()) {
String mSender = csr.getString(csr.getColumnIndex(KEY_SENDER));
String mMessage = csr.getString(csr.getColumnIndex(KEY_MESSAGE));
long mTime = csr.getLong(csr.getColumnIndex(KEY_TIME));
String mSeen = csr.getString(csr.getColumnIndex(KEY_SEEN));
String mTimer = csr.getString(csr.getColumnIndex(KEY_TIMER));
String mType = csr.getString(csr.getColumnIndex(KEY_TYPE));
messages.add(new SQLiteHelper(mSender, mMessage, mType, mSeen, mTimer, mTime));
mAdapter.notifyDataSetChanged();
}
mDatabaseReference.child("Messages").child(MessageSenderId).child(MessageRecieverId).setValue(null);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
sqlite.addListenerForSingleValueEvent(valueEventListener);
Adapter
public class MessagesAdapter extends RecyclerView.Adapter<MessagesAdapter.MessageViewHolder>{
ChatData mHelper;
Cursor csr;
private List<SQLiteHelper> mMessagesHelperList;
private FirebaseAuth mAuth;
public MessagesAdapter(List<SQLiteHelper> MessagesHelperList) {
this.mMessagesHelperList = MessagesHelperList;
}
public class MessageViewHolder extends RecyclerView.ViewHolder{
public TextView messageText;
public MessageViewHolder(View view) {
super(view);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(view.getContext());
mHelper = new ChatData(view.getContext(),"MessagePlus",null,1);
csr = mHelper.getAllQuestions3();
messageText = (TextView)view.findViewById(R.id.message_text_layout);
}
}
#Override
public MessageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View V = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_activity_chat,parent,false);
mAuth = FirebaseAuth.getInstance();
return new MessageViewHolder(V);
}
#Override
public void onBindViewHolder(final MessageViewHolder holder, int position) {
SQLiteHelper messagesHelper = mMessagesHelperList.get(position);
holder.messageText.setText(messagesHelper.getMessage());
}
#Override
public int getItemCount() {
return mMessagesHelperList.size();
}
I have another activity where i fetch sqlite data and show it in recyclerview and it works and i had achieved that the same way as this. Here too it used to work but then i added some features and moved around some code and now its not working and i have checked the whole code numerous times but still not finding why its not working...
The table and rows exists with data and the size of list too isnt null
Just discovered that the Adapter isnt getting called when i added Logs inside it. Thats where the problem is but idk why
Your problem is that you are adding the extra messages to the list that you first created your adapter so
instead of
messages.add(new SQLiteHelper(mSender, mMessage, mType, mSeen, mTimer, mTime));
mAdapter.notifyDataSetChanged();
do
mAdapter.add(new SQLiteHelper(mSender, mMessage, mType, mSeen, mTimer, mTime));
and in your adapter you have to add the add function like that
public void add(SQLiteHelper item){
if(mMessagesHelperList!=null){
mMessagesHelperList.add(item);
notifyDataSetChanged();
}
}
also
you have too much "trash" on your code, on your ValueEventListener you are trying to read the values of a cursor and not the ds (DataSnapshot). so probably your cursor there is empty. If the cursor is empty you don't add any item to the adapter, so the adapter don't have items to show, so onBindViewHolder correctly don't get called

How to Delete Firebase DataBase from onClick listener of Button

I'm using Recycle Adapter Class to show the Firebase Data in my app which contains the list of books that are available to purchase.
But once a book is sold, I want the user will be able to delete that book and will eventually delete from Firebase Database also on onClick of Button.
How can I do this?
Here is my Firebase Data Structure:
Here is RecycleAdapter Class
Here is my Adapter Data Class:
public class SubjectBooksAdapter extends RecyclerView.Adapter<SubjectBooksAdapter.MyViewHolder> {
ArrayList<Books> bookslist;
CardView cv;
FirebaseAuth fauth;
FirebaseDatabase database;
DatabaseReference dbreference;
Books b;
public SubjectBooksAdapter(ArrayList<Books> bookslist){
this.bookslist = bookslist;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout,parent,false);
return new MyViewHolder(v);
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView bookName,bookAuthor,bookDesc,bookPrice,bookCall;
ImageView iv;
Button delete;
MyViewHolder(final View itemView) {
super(itemView);
cv = (CardView) itemView.findViewById(R.id.my_card_view);
iv = (ImageView) itemView.findViewById(R.id.imageView);
database = FirebaseDatabase.getInstance();
dbreference = database.getReference("books");
bookName = (TextView) itemView.findViewById(R.id.bookName);
bookAuthor = (TextView) itemView.findViewById(R.id.bookAuthor);
bookDesc = (TextView) itemView.findViewById(R.id.bookDesc);
bookPrice = (TextView) itemView.findViewById(R.id.bookPrice);
bookCall = (TextView) itemView.findViewById(R.id.bookCall);
fauth = FirebaseAuth.getInstance();
delete = (Button) itemView.findViewById(R.id.delete);
}
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
database = FirebaseDatabase.getInstance();
dbreference = database.getReference("books");
b = bookslist.get(position);
holder.bookName.setText(b.getBname());
holder.bookAuthor.setText(b.getBauthor());
holder.bookDesc.setText(b.getBdesc());
holder.bookPrice.setText("Rs. "+b.getPrice());
holder.bookCall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Log.e("Current user is ", fauth.getCurrentUser().getEmail());
b = bookslist.get(position);
String[] arr = {b.getSelleremail(),b.getSellername(),b.getBname(),b.getBauthor()};
//Log.e("Seller is ",b.getSellername());
Intent in = new Intent(v.getContext(),Chat.class);
in.putExtra("seller",arr);
v.getContext().startActivity(in);
}
});
Glide.with(cv.getContext()).load(Uri.parse(b.getPics())).placeholder(R.drawable.bshelf).error(R.drawable.bshelf).into(holder.iv);
}
#Override
public int getItemCount() {
return bookslist.size();
}
}
And I'm using this in upload class to push Data in Firebase:
String bookid = dbreference.child("books").child(item).push().getKey();
dbreference.child("books").child(item).child(bookid).setValue(b);
You can put null against your bookid to remove it from it from database.
dbreference.child("books").child(bookId).setValue(null);
If you know the id of that book you should be able to remove the child with that id reference.
You have to implement the click listener as you did before with holder.bookCall.setOnClickListener(...);
Code:
holder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dbreference.child("books").child(bookId).remove();
}
});
I hope it helps you.
use this code:
DatabaseReference driverRef = FirebaseDatabase.getInstance().getReference().child("bname");
driverRef.removeValue();
if you delete whole database
use this
DatabaseReference driverRef = FirebaseDatabase.getInstance().getReference();
driverRef.removeValue();
//---------------------Use on Button click Listener--------
setContentView(R.layout.activity_main);
Button button=findViewById(R.id.btn);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DatabaseReference driverRef = FirebaseDatabase.getInstance().getReference().child("bname");
driverRef.removeValue();
}
});
This code will remove a book you want, just get the id of the book and place inside onClickListener:
dbreference.child("books").child(item).child(bookid).removeValue();
dbref.child("books").child("Computer Science").child(key).removeValue();

How can I populate a spinner with my Firebase database?

I want to populate a spinner instead of a ListView with data from Firebase.
The code below works fine with ListView. But how can I replace the ListView with a spinner? Hope someone can help me with this.
My research:
Firebase data to Spinner
Populatate the spinner from Firebase database
Here is my Main Activity:
public class Ansattliste extends AppCompatActivity {
DatabaseReference databaseAnsatt;
ListView lvansattliste;
Button btnleggtilansatt;
List<Ansatt> listansatt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ansattliste);
databaseAnsatt = FirebaseDatabase.getInstance().getReference("Ansatte");
lvansattliste = (ListView)findViewById(R.id.lvansattliste);
listansatt = new ArrayList<>();
btnleggtilansatt = (Button)findViewById(R.id.btnleggtilansatt);
btnleggtilansatt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent leggtil = new Intent(Ansattliste.this, Leggtilansatt.class);
startActivity(leggtil);
}
});
}
#Override
protected void onStart() {
super.onStart();
databaseAnsatt.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
listansatt.clear();
for (DataSnapshot ansattSnapshot : dataSnapshot.getChildren()) {
final Ansatt ansatt = ansattSnapshot.getValue(Ansatt.class);
listansatt.add(ansatt);
final listAnsatt adapter = new listAnsatt(Ansattliste.this, listansatt);
lvansattliste.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled (DatabaseError databaseError){
}
});
}
}
And my Adapter:
public class listAnsatt extends ArrayAdapter<Ansatt> {
private Activity context;
private List<Ansatt> listansatt;
public listAnsatt(Activity context, List<Ansatt> listansatt) {
super(context, R.layout.list_ansatt, listansatt);
this.context = context;
this.listansatt = listansatt;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.list_ansatt, null, true);
TextView tvansattnavn = (TextView) listViewItem.findViewById(R.id.tvansattnavn);
TextView tvansaattnr = (TextView) listViewItem.findViewById(R.id.tvansattnr);
Ansatt ansatt = listansatt.get(position);
tvansattnavn.setText(ansatt.getAnsattnavn());
tvansaattnr.setText(ansatt.getAnsattnr());
return listViewItem;
}
Firebase:
Firebase
You'd do something like following (I've adapted from Kotlin code I have here so possibility of some syntax errors)...have assumed for illustration that getAnsattnavn() is value you want to show in spinner. You'd still have listansatt which presumably you'd look up when item is selected in spinner.
In onDataChange:
List<String> optionList = new ArrayList<>();
for (DataSnapshot ansattSnapshot : dataSnapshot.getChildren()) {
final Ansatt ansatt = ansattSnapshot.getValue(Ansatt.class);
optionList.add(ansatt.getAnsattnavn());
listansatt.add(ansatt);
}
ArrayAdapter<CharSequence> adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, optionList);
spinnerControl.setAdapter(adapter);

Categories