Data fetched from sqlite not showing in recyclerview - java

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

Related

Can I have one recycleview that loads different datasets

I am working on mobile app which is for books.
I have recyclerview that has all categories - Romance, History etc.This RV is taking the data from Firebase.
What I want to do is following:
When the user clicks on Romance for example, a new activity needs to be opened. In that activity I want to have one RV loading the data-set with all books from that type.
Then, If the user opens History I want that data-set to be loaded into the same RV.
I want to avoid code repeating and what I am asking is - can I have 1 class with If statements that can handle the user choice and load the data-sets into one RV?
Would you be able to tell me how, if its possible?
Thank you !
Edit: Here is my code. What I did so far is Adapter, GetAndSet class, 2 Activities. To show categories into one RV I use 1 adapter and 1 GetAndSet class,1 XML file. I created 2 separate classes for romance and Comedy and inside them I do the connection to firebase.
Adapter:
public class CategoriesAdapter extends RecyclerView.Adapter {
Context mContext;
List<Categories> mData;
public CategoriesAdapter(Context mContext, List<Categories> mData) {
this.mContext = mContext;
this.mData = mData;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View row = LayoutInflater.from( mContext ).inflate( R.layout.row_attractions, parent, false );
return new MyViewHolder( row );
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.DesName.setText( mData.get( position ).getName() );
Glide.with( mContext ).load( mData.get( position ).getImage() ).into( holder.DesImage );
}
#Override
public int getItemCount() {
return mData.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView DesName;
ImageView DesImage;
public MyViewHolder(#NonNull View itemView) {
super( itemView );
itemView.setClickable( true );
mContext = itemView.getContext();
DesName = itemView.findViewById( R.id.DesName );
DesImage = itemView.findViewById( R.id.DesImage );
DesImage.setOnClickListener( this );
}
#Override
public void onClick(View v) {
final Intent intent;
Toast.makeText(itemView.getContext(),"Test",Toast.LENGTH_LONG ).show();
switch (getAdapterPosition()) {
case 0:
intent = new Intent( mContext, Romance.class );
break;
case 1:
intent = new Intent( mContext, Comedy.class );
break;
// case 2:
// intent = new Intent( mContext, RegentsPark.class );
// break;
default:
intent = new Intent( mContext, Home.class );
break;
}
mContext.startActivity( intent );
}
}
}
Romance class (Same as Comedy class,except the line with Firebase where I reffer to the dataset:
public class Romance extends AppCompatActivity {
RecyclerView categoriesRecyclerView ;
CategoriesAdapter categoriesAdapter ;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference ;
List<Categories> categoriesList;
private EditText mSearchField;
private ImageButton mSearchBtn;
private RecyclerView mResultList;
private DatabaseReference mUserDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_romance);
categoriesRecyclerView = findViewById(R.id.BookRV);
categoriesRecyclerView.setLayoutManager(new LinearLayoutManager(Romance.this));
categoriesRecyclerView.setHasFixedSize(true);
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference("ListParks");
// mUserDatabase = FirebaseDatabase.getInstance().getReference("Categories");
mSearchField = (EditText) findViewById(R.id.search_field);
mSearchBtn = (ImageButton) findViewById(R.id.search_btn);
mResultList = (RecyclerView) findViewById(R.id.result_list);
mResultList.setHasFixedSize(true);
mResultList.setLayoutManager(new LinearLayoutManager(this));
mSearchBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String searchText = mSearchField.getText().toString();
firebaseUserSearch(searchText);
}
});
}
private void firebaseUserSearch(String searchText) {
Toast.makeText(Romance.this, "Started Search", Toast.LENGTH_LONG).show();
Query firebaseSearchQuery = mUserDatabase.orderByChild("name").startAt(searchText).endAt(searchText + "\uf8ff");
FirebaseRecyclerAdapter<Users, UsersViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Users, UsersViewHolder>(
Users.class,
R.layout.list_layout,
UsersViewHolder.class,
firebaseSearchQuery
) {
#Override
protected void populateViewHolder(UsersViewHolder viewHolder, Users model, int position) {
viewHolder.setDetails(getApplicationContext(), model.getName(), model.getImage());
}
};
mResultList.setAdapter(firebaseRecyclerAdapter);
}
// View Holder Class
public static class UsersViewHolder extends RecyclerView.ViewHolder {
View mView;
public UsersViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setDetails(Context ctx, String userName, String userImage){
TextView user_name = (TextView) mView.findViewById(R.id.name_text);
ImageView user_image = (ImageView) mView.findViewById(R.id.profile_image);
user_name.setText(userName);
Glide.with(ctx).load(userImage).into(user_image);
}
}
#Override
protected void onStart() {
super.onStart();
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
categoriesList = new ArrayList<>();
for (DataSnapshot catsnap: dataSnapshot.getChildren()) {
Categories post = catsnap.getValue(Categories.class);
categoriesList.add(post) ;
}
//set Adapter
categoriesAdapter = new CategoriesAdapter(Romance.this,categoriesList);
categoriesRecyclerView.setAdapter(categoriesAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
Can I avoid creating different classes for each type of books?
If you want to know what category the user selected on the first RecyclerView:
Pass the category name/identifier to the activity you want to open when user clicks on the RecyclerView item. And then from the second activity get your data-set object according to the category you got from the previous activity and pass it to the adapter.
You can make a custom RecyclerView.Adapter.
Here is a good example:
Android Developers Documentation Example
When the adapter is initiated, you pass the data-set. This is the constructor of your custom RecyclerView.Adapter class:
public MyAdapter(String[] myDataset) {
mDataset = myDataset;
}
So every time you create the activity which is listing the books, you can create new RecyclerView.Adapter instance passing your data-set.
Put this somewhere in your onCreate method of the activity:
MyAdapter myAdapter = new MyAdapter(myDataset);
recyclerView.setAdapter(myAdapter);
When your activity is created, your RecyclerView will be loaded with the new data-set you provided the RecyclerView.Adapter with.
P.S.
If you are actually resuming the activity and have never destroyed it and want to change the adapter of already existing RecyclerView and refresh new items, you can do this in your onResume method
MyAdapter myAdapter = new MyAdapter(myDataset);
recyclerView.setAdapter(myAdapter);
myAdapter.notifyDataSetChanged();
Another way would be, again, if you are resuming (not creating) the activity and really don't want to create new Adapter and set it every time the activity resumes, then you will have to edit manually the data-set object you passed earlier to your custom adapter and call:
myAdapter.notifyDataSetChanged();
By saying edit I don't mean reassigning the variable! If you reassign the variable with another object, the adapter will loose the reference to that object and it will not work.

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.

RecyclerView is not populating items whereas Adapter and ArrayList already has data

recycerViewOrderNewItem and offlineOrderProductListProductList are two recyclerviews and those were initialized in onCreate() method.
recycerViewOrderNewItem = findViewById(R.id.recycerViewOrderNewItem);
recycerViewOrderNewItem.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
offlineOrderProductListProductList = findViewById(R.id.offlineOrderProductListProductList);
offlineOrderProductListProductList.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
The below is where I am retrieving my data as List<>
List<NewOrderEntryModel> allItemsOfOrder = new InitializeDatabase(OrderEntryActivity.this).myAppDatabaseInit.myDao().getAllNewOrderEntryModelByRefID(SalesID);
and I am setting adapter like this for both of them...
offlineOrderProductListProductList.setAdapter(new NewOrderEntryAdapter(OrderEntryActivity.this, (ArrayList<NewOrderEntryModel>) allItemsOfOrder));
recycerViewOrderNewItem.setAdapter(new NewOrderEntryAdapter(OrderEntryActivity.this, (ArrayList<NewOrderEntryModel>) allItemsOfOrder));
for offlineOrderProductListProductList recyclerview is working but for recycerViewOrderNewItem recyclerview is not working
I have debugged the code. ArrayList contains data.
Below is my adapter code...
public class NewOrderEntryAdapter extends RecyclerView.Adapter<NewOrderEntryAdapter.NewOrderEntryAdapterViewHolder>{
private Context context;
private ArrayList<NewOrderEntryModel> newOrderEntryModels;
public NewOrderEntryAdapter(Context context, ArrayList<NewOrderEntryModel> newOrderEntryModels) {
this.context = context;
this.newOrderEntryModels = newOrderEntryModels;
}
#NonNull
#Override
public NewOrderEntryAdapterViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.list_item_order_entry_detail,parent,false);
return new NewOrderEntryAdapterViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull NewOrderEntryAdapterViewHolder holder, final int position) {
NewOrderEntryModel orderEntryModel = newOrderEntryModels.get(position);
//Data
final String name = orderEntryModel.getProductName();
final String totalPrice = String.valueOf(orderEntryModel.getPBSalesTotal());
final String code = String.valueOf(orderEntryModel.getPCode());
final String quantity = String.valueOf(orderEntryModel.getPBInQty());
final String price = String.valueOf(orderEntryModel.getPBSalesPrice());
final String productID = String.valueOf(orderEntryModel.getPBProductID());
// Binding
holder.tvProductNameOrderEntry.setText(name);
holder.tvProductTotalPriceOrderEntry.setText(totalPrice);
holder.tvProductCodeOrderEntry.setText(code);
holder.tvProductQuantityOrderEntry.setText(quantity);
holder.tvProductPriceOrderEntry.setText(price);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(context, "Reference id: "+orderEntryModel.getPBRefID()+" Table ID: "+orderEntryModel.getID(), Toast.LENGTH_SHORT).show();
if(orderEntryModel.getPBRefID()==null){
//Toast.makeText(context, "Reference id: "+orderEntryModel.getPBRefID()+" Table ID: "+orderEntryModel.getID(), Toast.LENGTH_SHORT).show();
openDetailActivity(String.valueOf(position),"","",name,totalPrice,code,quantity,price,productID);
}else {
Toast.makeText(context, "Reference id: "+orderEntryModel.getPBRefID()+" Table ID: "+orderEntryModel.getID(), Toast.LENGTH_SHORT).show();
openDetailActivity(String.valueOf(position),Integer.toString(orderEntryModel.getID()),orderEntryModel.getPBRefID(),name,totalPrice,code,quantity,price,productID);
}
//Toast.makeText(context, context.toString(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return newOrderEntryModels.size();
}
public class NewOrderEntryAdapterViewHolder extends RecyclerView.ViewHolder{
public TextView tvProductNameOrderEntry
,tvProductTotalPriceOrderEntry
,tvProductCodeOrderEntry
,tvProductQuantityOrderEntry
,tvProductPriceOrderEntry;
public NewOrderEntryAdapterViewHolder(View itemView) {
super(itemView);
tvProductNameOrderEntry = itemView.findViewById(R.id.tvProductNameOrderEntry);
tvProductTotalPriceOrderEntry = itemView.findViewById(R.id.tvProductTotalPriceOrderEntry);
tvProductCodeOrderEntry = itemView.findViewById(R.id.tvProductCodeOrderEntry);
tvProductQuantityOrderEntry = itemView.findViewById(R.id.tvProductQuantityOrderEntry);
tvProductPriceOrderEntry = itemView.findViewById(R.id.tvProductPriceOrderEntry);
}
}
public void openDetailActivity(String position,
String id,
String pbRef,
String productName,
String totalPrice,
String productCode,
String quantity,
String productPrice,
String productID){
Intent intent = new Intent(context, NewItemDetailActivity.class);
intent.putExtra("position",position);
intent.putExtra("id",id);
intent.putExtra("pbRef",pbRef);
intent.putExtra("productName",productName);
intent.putExtra("totalPrice",totalPrice);
intent.putExtra("productCode",productCode);
intent.putExtra("quantity",quantity);
intent.putExtra("productPrice",productPrice);
intent.putExtra("productID",productID);
context.startActivity(intent);
}
}
please help me out with this problem...
I think you should initialize your adapter and recyclerview clearly.
allItemsOfOrder can be global like this
List<NewOrderEntryModel> allItemsOfOrder = new ArrayList<>();
Take the code below as an example:
recyclerView = (RecyclerView) findViewById(R.id.recycerViewOrderNewItem);
mAdapter = new NewOrderEntryAdapter(this,allItemsOfOrder);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
Then you should add orders to your list
allItemsOfOrder can be global like this
allItemsOfOrder.add(/*Something*/);
Then you should notify your adapter like below...
mAdapter.notifyDataSetChanged();
you can use this link as a reference.

Is it possible to "Archive" Firebase records

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);
}

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