Searching in android with Firebase - android

I'm using the library Material Search Bar to search my Firebase Database, but it doesn't work.
Right here is the layout and it is assumed that when I click on the search bar should give me some suggestions and also to look for products but it is not
View
My Firebase Database
Firebase DataBase
Here is my Home.java where i put the searchBar
public class Home extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
FirebaseDatabase database;
DatabaseReference product;
TextView userName;
RecyclerView recycler_prod;
RecyclerView.LayoutManager layoutManager;
FirebaseRecyclerAdapter<Product,ProductViewHolder> adapter;
FirebaseRecyclerAdapter<Product, ProductViewHolder> searchadapter;
MaterialSearchBar searchBar;
String ProductId = "";
List<String> suggestList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
database=FirebaseDatabase.getInstance();
product=database.getReference("Product");
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View headerView = navigationView.getHeaderView(0);
userName= headerView.findViewById(R.id.idUserName);
userName.setText(Common.currentuser.getName());
recycler_prod = findViewById(R.id.recycler_card);
recycler_prod.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recycler_prod.setLayoutManager(layoutManager);
loadProducts();
searchBar = findViewById(R.id.searchBar);
searchBar.setPlaceHolder("Productos");
loadSuggest();
searchBar.setLastSuggestions(suggestList);
searchBar.setCardViewElevation(10);
searchBar.addTextChangeListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
List<String> suggest = new ArrayList<String>();
for (String search : suggestList) {
if (search.toLowerCase().contains(searchBar.getText().toLowerCase()))
suggest.add(search);
}
searchBar.setLastSuggestions(suggest);
}
#Override
public void afterTextChanged(Editable s) {
}
});
searchBar.setOnSearchActionListener(new MaterialSearchBar.OnSearchActionListener() {
#Override
public void onSearchStateChanged(boolean enabled) {
if (!enabled)
recycler_prod.setAdapter(adapter);
}
#Override
public void onSearchConfirmed(CharSequence text) {
startSearch(text);
}
#Override
public void onButtonClicked(int buttonCode) {
}
});
}
private void startSearch(CharSequence text) {
searchadapter = new FirebaseRecyclerAdapter<Product, ProductViewHolder>(
Product.class,
R.layout.card_item,
ProductViewHolder.class,
product.orderByChild("Name").equalTo(text.toString())
) {
#Override
protected void populateViewHolder(ProductViewHolder viewHolder, Product model, int position) {
viewHolder.txtProductName.setText(model.getName());
Picasso.get().load(model.getImage())
.into(viewHolder.imageProductView);
final Product local = model;
viewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
Intent details = new Intent(Home.this, ProductDetail.class);
details.putExtra("ProductId", searchadapter.getRef(position).getKey());
startActivity(details);
}
});
}
};
recycler_prod.setAdapter(searchadapter);
}
private void loadSuggest() {
product.orderByChild("ProductId").equalTo(ProductId)
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot postSnapshot:dataSnapshot.getChildren()){
Product item = postSnapshot.getValue(Product.class);
suggestList.add(item.getName());
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void loadProducts() {
adapter = new FirebaseRecyclerAdapter<Product, ProductViewHolder>(Product.class,
R.layout.card_item,
ProductViewHolder.class,
product) {
#Override
protected void populateViewHolder(ProductViewHolder holder, Product model, int position) {
holder.txtProductName.setText(model.getName());
holder.txtProductDesc.setText(model.getDescription());
holder.txtProductPrice.setText("$" + model.getPrice());
Picasso.get().load(model.getImage())
.into(holder.imageProductView);
final Product clickItem = model;
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
Intent details = new Intent(Home.this, ProductDetail.class);
details.putExtra("ProductId", adapter.getRef(position).getKey());
startActivity(details);
}
});
}
};
recycler_prod.setAdapter(adapter);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_search) {
// Handle the camera action
} else if (id == R.id.nav_map) {
Intent mapa = new Intent(Home.this,Maps.class);
startActivity(mapa);
} else if (id == R.id.nav_log_out) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
My Product.java Model
public class Product {
private String Description, Name, Image,Price,Link;
public Product() {
}
public Product(String description, String name, String image, String price, String link) {
Description = description;
Name = name;
Image = image;
Price = price;
Link = link;
}
public String getLink() {
return Link;
}
public void setLink(String link) {
Link = link;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getImage() {
return Image;
}
public void setImage(String image) {
Image = image;
}
public String getPrice() {
return Price;
}
public void setPrice(String price) {
Price = price;
}
}
My ProductViewHolder.java
public class ProductViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView txtProductName,txtProductDesc,txtProductPrice;
public ImageView imageProductView;
private ItemClickListener itemClickListener;
public ProductViewHolder(#NonNull View itemView) {
super(itemView);
txtProductName = itemView.findViewById(R.id.name);
txtProductDesc = itemView.findViewById(R.id.description);
txtProductPrice = itemView.findViewById(R.id.price);
imageProductView = itemView.findViewById(R.id.thumbnail);
itemView.setOnClickListener(this);
}
public void setItemClickListener(ItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
#Override
public void onClick(View v) {
itemClickListener.onClick(v,getAdapterPosition(),false);
}
}
Thank you for your attention

In your startSearch method, replace your .equalto with .startAt. See if it works

Related

SearchView on RecyclerView no work how to fix?

Hello I implemented a search but when trying to filter nothing happens someone knows some way to make it work correctly, I can't identify where it is wrong. Thanks in advance. any help is welcome.
Below are codes of my activity where is the recycler view. And model contacts.
I really don't know what I'm doing wrong.
Contacts Model
public class Contacts {
public String name, status, image;
public Contacts()
{
}
public Contacts(String name, String status, String image) {
this.name = name;
this.status = status;
this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
My Activity
public class FindFriendsActivity extends AppCompatActivity
{
private Toolbar mToolbar;
private RecyclerView FindFriendsRecyclerList;
private DatabaseReference UsersRef;
private SearchView searchView;
private Query query;
private FirebaseRecyclerOptions<ColorSpace.Model> options;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_friends);
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
FindFriendsRecyclerList = (RecyclerView) findViewById(R.id.find_friends_recycler_list);
FindFriendsRecyclerList.setLayoutManager(new LinearLayoutManager(this));
mToolbar = (Toolbar) findViewById(R.id.find_friends_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("Find Friends");
searchView = findViewById(R.id.materialSearchPrincipal);
}
#Override
protected void onStart()
{
super.onStart();
FirebaseRecyclerOptions<Contacts> options =
new Builder<Contacts>()
.setQuery(UsersRef, Contacts.class)
.build();
FirebaseRecyclerAdapter<Contacts, FindFriendViewHolder> adapter =
new FirebaseRecyclerAdapter<Contacts, FindFriendViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull FindFriendViewHolder holder, final int position, #NonNull Contacts model)
{
holder.userName.setText(model.getName());
holder.userStatus.setText(model.getStatus());
Picasso.get().load(model.getImage()).placeholder(R.drawable.profile_image).into(holder.profileImage);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
String visit_user_id = getRef(position).getKey();
Intent profileIntent = new Intent(FindFriendsActivity.this, ProfileActivity.class);
profileIntent.putExtra("visit_user_id", visit_user_id);
startActivity(profileIntent);
}
});
}
#NonNull
#Override
public FindFriendViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i)
{
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.users_display_layout, viewGroup, false);
FindFriendViewHolder viewHolder = new FindFriendViewHolder(view);
return viewHolder;
}
};
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
private void fetch(Query query) {
FirebaseRecyclerOptions<Contacts> options =
new Builder<Contacts>()
.setQuery(query, Contacts.class)
.build();
}
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
Query query = FirebaseDatabase.getInstance()
.getReference()
.child("User").orderByChild("name").equalTo(s);
if(s.equals("")){
query = FirebaseDatabase.getInstance()
.getReference()
.child("name");
}
fetch(query);
return false;
}
});
FindFriendsRecyclerList.setAdapter(adapter);
adapter.startListening();
}
public static class FindFriendViewHolder extends RecyclerView.ViewHolder
{
TextView userName, userStatus;
CircleImageView profileImage;
public FindFriendViewHolder(#NonNull View itemView)
{
super(itemView);
userName = itemView.findViewById(R.id.user_profile_name);
userStatus = itemView.findViewById(R.id.user_status);
profileImage = itemView.findViewById(R.id.users_profile_image);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.options_menu, menu);
MenuItem item = menu.findItem(R.id.menuPesquisa);
return true;
}
}
You need a new reference to adapter in fetch() method, because after every search the returned item count is changing. That's why in my example I have done like this in the fetch() method:
adapter = new CustomFirebaseRecylerAdapter<Model, CustomFirebaseRecylerAdapter.ViewHolder>(options);
adapter.startListening();
recyclerView.setAdapter(adapter);
try creating a new adapter instance in the fetch() method and then setting up the following:
adapter.startListening();
FindFriendsRecyclerList.setAdapter(adapter);

RecyclerView with different types and different adapter

and thank you for your attention to my request.
I'm a newbie on Andorid Studio and I'm developing an App, it has to show a list of Events, Courses and News. There is a DrawerLayout which allow navigating into Event's, course's and news's area, each area has each specific RecyclerView, but into the home activity, I have to show all the items (Event, Course and News).
I create an Adapter for each item (because they have different properties) and each section (fragment) works properly but now I'm stuck with the main activity (the home).
Here are the models for explaining the difference between them:
Event
public class Event {
private int id;
private String title;
private String description;
private LocalDateTime startingDate;
private LocalDateTime endingDate;
private String cost;
private String website;
private Category category;
private Venue venue;
private Organizer organizer;
private String status;
private int resImage;
public Event(int id, String title, String description, LocalDateTime startingDate, LocalDateTime endingDate, String cost, String website, Category category, Venue venue, Organizer organizer, int image) {
this.id = id;
this.title = title;
this.description = description;
this.startingDate = startingDate;
this.endingDate = endingDate;
this.cost = cost;
this.website = website;
this.category = category;
this.venue = venue;
this.organizer = organizer;
this.resImage = image;
}
public Event(){}
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public void setTitle(String name) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public LocalDateTime getStartingDate() {
return startingDate;
}
public void setStartingDate(LocalDateTime startingDate) {
this.startingDate = startingDate;
}
public LocalDateTime getEndingDate() {
return endingDate;
}
public void setEndingDate(LocalDateTime endingDate) {
this.endingDate = endingDate;
}
public String getCost() {
return cost;
}
public void setCost(String cost) {
this.cost = cost;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public Category getCategory() {
return category;
}
public Venue getVenue() {
return venue;
}
public Organizer getOrganizer() {
return organizer;
}
public String getStatus() {
return status;
}
public int getResImage() {
return resImage;
}
}
News:
public class News {
private int id;
private String title;
private String content;
private int resImage;
public News(int id, String title, String content, int image) {
this.id = id;
this.title = title;
this.content = content;
this.resImage = image;
}
public News(){}
public int getId(){
return this.id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setDescription(String description) {
this.content = content;
}
public int getResImage() {
return resImage;
}
public void setResImage(int resImage) {
this.resImage = resImage;
}
}
Courses
public Course(int id, String title, String content, float price, LocalDate startingDate, int availablePlace, Teacher teacher, CourseCategory courseCategory, Location location, Duration duration, Level level, int resImage) {
this.id = id;
this.title = title;
this.content = content;
this.price = price;
this.startingDate = startingDate;
this.availablePlace = availablePlace;
this.teacher = teacher;
this.courseCategory = courseCategory;
this.location = location;
this.duration = duration;
this.level = level;
this.resImage = resImage;
}
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public LocalDate getStartingDate() {
return startingDate;
}
public void setStartingDate(LocalDate startingDate) {
this.startingDate = startingDate;
}
public int getAvailablePlace() {
return availablePlace;
}
public void setAvailablePlace(int availablePlace) {
this.availablePlace = availablePlace;
}
public Teacher getTeacher() {
return teacher;
}
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
public CourseCategory getCourseCategory() {
return courseCategory;
}
public void setCourseCategory(CourseCategory courseCategory) {
this.courseCategory = courseCategory;
}
public Location getLocation() {
return location;
}
public void setLocation(Location location) {
this.location = location;
}
public Duration getDuration() {
return duration;
}
public void setDuration(Duration duration) {
this.duration = duration;
}
public Level getLevel() {
return level;
}
public int getResImage() {
return resImage;
}
public void setResImage(int resImage) {
this.resImage = resImage;
}
}
Here is the Adapters:
EventAdapter
public class EventViewAdapter extends RecyclerView.Adapter<EventViewAdapter.EventViewHolder> {
ArrayList<Event> eventList;
Context context;
public EventViewAdapter(ArrayList<Event> eventList, Context context) {
this.eventList = eventList;
this.context = context;
}
public EventViewAdapter() {
}
public static class EventViewHolder extends RecyclerView.ViewHolder {
ImageView eventImage;
TextView startingDate, place, title;
LinearLayout cellLayout;
EventViewHolder(View eventView) {
super(eventView);
eventImage = eventView.findViewById(R.id.event_image);
startingDate = eventView.findViewById(R.id.event_starting_date);
place = eventView.findViewById(R.id.event_place);
title = eventView.findViewById(R.id.event_title);
cellLayout = eventView.findViewById(R.id.event_cell_layout);
}
}
#NonNull
#Override
public EventViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.event_cell_def, parent, false);
EventViewHolder evh = new EventViewHolder(view);
return evh;
}
#Override
public void onBindViewHolder(#NonNull EventViewHolder holder, int position) {
final String title = eventList.get(position).getTitle();
final String description = eventList.get(position).getDescription();
final String place = eventList.get(position).getVenue().getCity();
final String address = eventList.get(position).getVenue().getAddress();
final String startDate = String.valueOf(eventList.get(position).getStartingDate().toLocalDate());
final String startTime = String.valueOf(eventList.get(position).getStartingDate().getHour() + ":" + String.valueOf(eventList.get(position).getStartingDate().getMinute()));
final String endDate = String.valueOf(eventList.get(position).getEndingDate().toLocalDate());
final String cost = eventList.get(position).getCost();
final String website = eventList.get(position).getWebsite();
final String category = eventList.get(position).getCategory().getName();
final String organizer = eventList.get(position).getOrganizer().getOrganizer();
final String organizerWebsite = eventList.get(position).getOrganizer().getWebsite();
final int image = eventList.get(position).getResImage();
holder.eventImage.setImageResource(image);
holder.startingDate.setText(startDate);
holder.place.setText(place);
holder.title.setText(title);
holder.cellLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), DetailEventActivity.class);
intent.putExtra("title", title);
intent.putExtra("description", description);
intent.putExtra("place", place);
intent.putExtra("address", address);
intent.putExtra("startDate", startDate);
intent.putExtra("startTime", startTime);
intent.putExtra("endDate", endDate);
intent.putExtra("cost", cost);
intent.putExtra("website", website);
intent.putExtra("category", category);
intent.putExtra("organizer", organizer);
intent.putExtra("orgWebsite", organizerWebsite);
intent.putExtra("image", image);
v.getContext().startActivity(intent);
Toast.makeText(context, "Hai premuto su: " + title, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return eventList.size();
}
public void eventSetSearchOperation(ArrayList<Event> newList){
eventList = new ArrayList<>();
eventList.addAll(newList);
notifyDataSetChanged();
}
}
CourseAdapter:
public class CourseViewAdapter extends RecyclerView.Adapter<CourseViewAdapter.CourseViewHolder> {
ArrayList<Course> courseList;
Context context;
public CourseViewAdapter(ArrayList<Course> courseList, Context context) {
this.courseList = courseList;
this.context = context;
}
public CourseViewAdapter(){}
public static class CourseViewHolder extends RecyclerView.ViewHolder {
ImageView courseImage;
TextView startingDate, place, title;
LinearLayout courseLinear;
CourseViewHolder(View courseView){
super(courseView);
courseImage = courseView.findViewById(R.id.course_image);
startingDate = courseView.findViewById(R.id.course_starting_date);
place = courseView.findViewById(R.id.course_place);
title = courseView.findViewById(R.id.course_title);
courseLinear = courseView.findViewById(R.id.course_cell_layout);
}
}
#NonNull
#Override
public CourseViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.course_cell_def, parent, false);
CourseViewHolder cvh = new CourseViewHolder(view);
return cvh;
}
#Override
public void onBindViewHolder(#NonNull CourseViewHolder holder, int position) {
final String title = courseList.get(position).getTitle();
final String category = courseList.get(position).getCourseCategory().getName();
final String description = courseList.get(position).getContent();
final String place = courseList.get(position).getLocation().getName();
final String startDate = String.valueOf(courseList.get(position).getStartingDate());
final int availablePlace = courseList.get(position).getAvailablePlace();
final String teacher = courseList.get(position).getTeacher().getName();
final String teacherEmail = courseList.get(position).getTeacher().getEmail();
final String teacherMobile = courseList.get(position).getTeacher().getPhone();
final String duration = courseList.get(position).getDuration().getName();
final String level = courseList.get(position).getLevel().getName();
final String price = String.valueOf(courseList.get(position).getPrice());
final int image = courseList.get(position).getResImage();
holder.courseImage.setImageResource(image);
holder.startingDate.setText(startDate);
holder.place.setText(place);
holder.title.setText(title);
holder.courseLinear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), DetailCourseActivity.class);
intent.putExtra("title", title);
intent.putExtra("category", category);
intent.putExtra("content", description);
intent.putExtra("startDate", startDate);
intent.putExtra("availablePlace", availablePlace);
intent.putExtra("teacher", teacher);
intent.putExtra("teacherEmail", teacherEmail);
intent.putExtra("teacherMobile", teacherMobile);
intent.putExtra("duration", duration);
intent.putExtra("price", price);
intent.putExtra("place", place);
intent.putExtra("level", level);
intent.putExtra("image", image);
v.getContext().startActivity(intent);
Toast.makeText(context, "Hai premuto su: " + title, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return courseList.size();
}
public void courseSetSearchOperation(ArrayList<Course> newList){
courseList = new ArrayList<>();
courseList.addAll(newList);
notifyDataSetChanged();
}
}
News:
public class NewsViewAdapter extends RecyclerView.Adapter<NewsViewAdapter.NewsViewHolder> {
ArrayList<News> newsList;
Context context;
public NewsViewAdapter(ArrayList<News> newsList, Context context) {
this.newsList = newsList;
this.context = context;
}
public NewsViewAdapter(){}
public static class NewsViewHolder extends RecyclerView.ViewHolder {
ImageView newsImage;
TextView newsTitle, newsContent;
LinearLayout newsLayout;
NewsViewHolder(View newView){
super(newView);
newsImage = newView.findViewById(R.id.news_image);
newsTitle = newView.findViewById(R.id.news_title);
newsContent = newView.findViewById(R.id.news_content);
newsLayout = newView.findViewById(R.id.news_cell_layout);
}
}
#NonNull
#Override
public NewsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.news_cell_def, parent, false);
NewsViewHolder nvh = new NewsViewHolder(view);
return nvh;
}
#Override
public void onBindViewHolder(#NonNull NewsViewHolder holder, int position) {
final String title = newsList.get(position).getTitle();
final String content = newsList.get(position).getContent();
final int image = newsList.get(position).getResImage();
holder.newsImage.setImageResource(image);
holder.newsTitle.setText(title);
holder.newsContent.setText(content);
holder.newsLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), DetailNewsActivity.class);
intent.putExtra("title", title);
intent.putExtra("content", content);
intent.putExtra("image", image);
v.getContext().startActivity(intent);
Toast.makeText(context, "Premuto su: " + title, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return newsList.size();
}
public void newsSetSearchOperation(ArrayList<News> newList){
newsList = new ArrayList<>();
newsList.addAll(newList);
notifyDataSetChanged();
}
}
Each specific list of item is into a fragment, indeed here is the Main Activity (home), where I would like to display a RecyclerView of all the itmes:
public class MainActivity extends AppCompatActivity {
private DrawerLayout drawerLayout;
private NavigationView mNavigationView;
private Toolbar toolbar;
private ActionBarDrawerToggle drawerToggle;
private FloatingActionButton fab;
private RecyclerView mRecyclerView;
private ImageView openFilter;
private SearchView searchView;
private DataMock dataMock = new DataMock();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.recycler_view_main);
drawerLayout = findViewById(R.id.drawer_layout);
mNavigationView = findViewById(R.id.nav_view);
toolbar = findViewById(R.id.toolbar);
openFilter = findViewById(R.id.filter_icon);
searchView = findViewById(R.id.action_search);
fab = findViewById(R.id.fab);
fab.show();
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
searchView.setQueryHint(getString(R.string.search_hint));
drawerToggle = setupDrawerToggle();
drawerToggle.setDrawerIndicatorEnabled(true);
drawerToggle.syncState();
drawerLayout.setDrawerListener(drawerToggle);
drawerLayout.setDrawerListener(new DrawerLayout.SimpleDrawerListener() {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
});
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment nextFragment;
switch (menuItem.getItemId()){
case R.id.event_list:
nextFragment = new EventFragment();
break;
case R.id.course_list:
nextFragment = new CourseFragment();
break;
case R.id.news_list:
nextFragment = new NewsFragment();
break;
default:
throw new IllegalArgumentException("No Fragment for the given menu item");
}
if (nextFragment != null){
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.anchor_point, nextFragment)
.commit();
menuItem.setChecked(true);
setTitle(menuItem.getTitle());
drawerLayout.closeDrawer(mNavigationView);
}
return false;
}
});
openFilter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BottomSheetDialog filterDialog = new BottomSheetDialog();
filterDialog.show(getSupportFragmentManager(), "filter dialog opened!");
}
});
// mRecyclerView.setHasFixedSize(true);
// LinearLayoutManager layoutManager = new LinearLayoutManager(this);
// mRecyclerView.setLayoutManager(layoutManager);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
switch (item.getItemId()) {
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
private ActionBarDrawerToggle setupDrawerToggle() {
// NOTE: Make sure you pass in a valid toolbar reference. ActionBarDrawToggle() does not require it
// and will not render the hamburger icon without it.
return new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);
}
public void backToHome(View view){
for (Fragment fragment : getSupportFragmentManager().getFragments()){
if (fragment != null && (fragment instanceof CourseFragment || fragment instanceof EventFragment || fragment instanceof NewsFragment)){
getSupportFragmentManager().beginTransaction().remove(fragment).commit();
toolbar.setTitle("WePress");
fab.show();
}
}
Toast.makeText(this, "Premuto sul logo", Toast.LENGTH_SHORT).show();
drawerLayout.closeDrawer(mNavigationView);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
drawerToggle.onConfigurationChanged(newConfig);
}
public void addItem(View view){
PopupMenu popupMenu = new PopupMenu(MainActivity.this, fab);
popupMenu.getMenuInflater().inflate(R.menu.fab_main_menu, popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()){
case R.id.add_event:
Toast.makeText(MainActivity.this, "Pronti per aggiungere un evento", Toast.LENGTH_SHORT).show();
Intent intentEvent = new Intent(MainActivity.this, AddItemActivity.class);
intentEvent.putExtra("isFrom", "event");
startActivity(intentEvent);
break;
case R.id.add_course:
Toast.makeText(MainActivity.this, "Pronti per aggiungere un corso", Toast.LENGTH_SHORT).show();
Intent intentCourse = new Intent(MainActivity.this, AddItemActivity.class);
intentCourse.putExtra("isFrom", "course");
startActivity(intentCourse);
break;
case R.id.add_news:
Toast.makeText(MainActivity.this, "Pronti per aggiungere una news", Toast.LENGTH_SHORT).show();
Intent intentNews = new Intent(MainActivity.this, AddItemActivity.class);
intentNews.putExtra("isFrom", "news");
startActivity(intentNews);
break;
}
return true;
}
});
popupMenu.show();
}
}
if it's possible to show the list with differents layouts, can you also suggest a way to improve the quality of my code avoiding to repeat lines of code? If I'm not wrong, I would like to re-use each Adapter or part of them that I can put into a specific class (?).
Thank you so much for your help!
If I'm missing some information, please ask me in order to edit the post.
You must do only one adapter (using view type) with a view model class
that contain either an event or a news or a course
the adapter should be something like that:
public class EventViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int TYPE_EVENT = 10;
private static final int TYPE_COURSE = 11;
private static final int TYPE_NEWS = 12;
ArrayList<EventViewModel> eventList;
Context context;
public EventViewAdapter(ArrayList<EventViewModel> eventList, Context context) {
this.eventList = eventList;
this.context = context;
}
public EventViewAdapter() {
}
#Override
public int getItemViewType(int position) {
EventViewModel event = eventList.get(position);
if (event.isEvent()) {
return TYPE_EVENT ;
} else if(event.isCourse()) {
return TYPE_COURSE;
} else {
return TYPE_NEWS;
}
}
public static class EventViewHolder extends RecyclerView.ViewHolder {
ImageView eventImage;
//....
EventViewHolder(View eventView) {
super(eventView);
eventImage = eventView.findViewById(R.id.event_image);
//.....
}
}
public static class CourseViewHolder extends RecyclerView.ViewHolder {
ImageView courseImage;
//.....
CourseViewHolder(View courseView) {
super(courseView);
courseImage = courseView.findViewById(R.id.course_image);
//.....
}
public static class NewsViewHolder extends RecyclerView.ViewHolder {
ImageView newsImage;
//.....
NewsViewHolder(View newView){
super(newView);
newsImage = newView.findViewById(R.id.news_image);
//.....
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if (viewType == TYPE_EVENT) {
View rootView = LayoutInflater.from(parent.getContext()).inflate(R.layout.event_cell_def, parent, false);
return new EventViewHolder (rootView);
} else if (viewType == TYPE_COURSE) {
View rootView = LayoutInflater.from(parent.getContext()).inflate(R.layout.course_cell_def, parent, false);
return new CourseViewHolder(rootView);
} else {
View rootView = LayoutInflater.from(parent.getContext()).inflate(R.layout.news_cell_def, parent, false);
return new NewsViewHolder(rootView);
}
}
#Override
public void onBindViewHolder(#NonNull EventViewHolder holder, int position)
{
final EventViewModel eventViewModel = eventList.get(position);
if (eventViewModel .isEvent()) {
onBindEvent(holder, eventViewModel.getEvent());
} else if(eventViewModel .isCourse()) {
onBindCourse(holder, eventViewModel.getCourse());
} else {
onBindNews(holder, eventViewModel.getNews());
}
}
private void onBindEvent(RecyclerView.ViewHolder holder, Event event) {
EventViewHolder eventHolder= (EventViewHolder ) holder;
final String title = event.getTitle();
final String description = event.getDescription();
// others ...
holder.eventImage.setImageResource(image);
holder.startingDate.setText(startDate);
// others ...
holder.cellLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
// ...
}
#Override
public int getItemCount() {
return eventList.size();
}
public void eventSetSearchOperation(ArrayList<Event> newList){
eventList = new ArrayList<>();
eventList.addAll(newList);
notifyDataSetChanged();
}
}
And a View Model classes like that :
public class EventViewModel() {
private Event mEvent;
private Course mCourse;
private News mNews;
private EventViewModel(Event event, Course course, News news) {
this.mEvent = event;
this.mCourse = course;
this.mNews = news;
}
public boolean isEvent() {
return mEvent != null
}
public boolean isCourse() {
return mCourse != null
}
public boolean isNews() {
return mNews != null
}
public static EventViewModel getEventInstance(Event event) {
return new EventViewModel(event, null, null
}
public static EventViewModel getCourseInstance(Course course) {
return new EventViewModel(null, course, null
}
public static EventViewModel getNewsInstance(News news) {
return new EventViewModel(null, null, news
}
public Event getEvent() {
return mEvent;
}
public Event getCourse() {
return mScore;
}
public Event getNews() {
return mNews;
}
}
You can use this adapter in all of your fragments (event, course, news) and each fragment contaions a list of EventViewModel with only its specific type. The adapter display in the main activity contains EventViewModel of all types to display all events.

How do I access the children in my firebase database and display them in the activity according to the listview item selected

I have my app whwere i need to display the information regarding the item that is clicked on in the listview. However that is the data stored in my firebase database. The database looks like this:
Now i want to click on the listview item so that i can display the information corresponding to it in a different activity.
The code for the MainActivity where the listview and Firebase is stored is:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
DrawerLayout drawer;
ActionBarDrawerToggle toggle;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference mDatabaseReference;
private ChildEventListener mChildEventListener;
private FirebaseAuth mFirebaseAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
public TicketAdapter adapter;
private final static int RC_SIGN_IN = 2;
public String mUsername;
public static String ComplaintID;
public static String StatusImg;
public static String TicketCat;
public static String SubCat;
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mFirebaseAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
mDatabaseReference = mFirebaseDatabase.getReference().child("Ticket");
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = mFirebaseAuth.getCurrentUser();
if (user != null) {
onSignedInInitialized(user.getDisplayName());
} else {
onSignedOutCleanup();
startActivityForResult(
getInstance()
.createSignInIntentBuilder()
.setIsSmartLockEnabled(false)
.setAvailableProviders(Arrays.asList(
new AuthUI.IdpConfig.EmailBuilder().build(),
new AuthUI.IdpConfig.GoogleBuilder().build()))
.build(),
RC_SIGN_IN);
}
}
};
final ListView listView = (ListView)findViewById(R.id.lvTicket);
final ArrayList<Ticket> arrayOfTicket = new ArrayList<>();
adapter = new TicketAdapter(this, arrayOfTicket);
listView.setAdapter(adapter);
mDatabaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
Ticket ticket = (Ticket)dataSnapshot.getValue(Ticket.class);
adapter.add(ticket);
adapter.notifyDataSetChanged();
assert ticket != null;
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
mDatabaseReference = FirebaseDatabase.getInstance().getReference();
final DatabaseReference TicketCategory = mDatabaseReference.child("Ticket").child("ticketCategory");
TicketCategory.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String TCategory = dataSnapshot.child("ticketCategory").getValue(String.class);
TicketCat = TCategory;
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Ticket ticket = new Ticket();
Intent intent = new Intent(view.getContext(), ComplaintDetail.class);
startActivity(intent);
}
});
final Button button = (Button) findViewById(R.id.complaintbutton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, TicketCategory.class);
startActivity(intent);
}
}
);
}
#Override
protected void onPostCreate(Bundle savedInstanceState)
{
super.onPostCreate(savedInstanceState);
toggle.syncState();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId())
{
case R.id.action_settings:
{
AuthUI.getInstance().signOut(this);
return true;
}
default:
return super.onOptionsItemSelected(item);
}
}
private void detachDatabaseReadListener()
{
if(mChildEventListener != null)
{
mDatabaseReference.removeEventListener(mChildEventListener);
mChildEventListener = null;
}
}
#Override
protected void onResume()
{
super.onResume();
mFirebaseAuth.addAuthStateListener(mAuthStateListener);
}
#Override
protected void onPause()
{
super.onPause();
mFirebaseAuth.removeAuthStateListener(mAuthStateListener);
}
private void onSignedInInitialized(String username)
{
mUsername = username;
// attachDatabaseReadListener();
}
private void onSignedOutCleanup()
{
mUsername = null;
}
This is the code for the activity where i want to display the children:
public class ComplaintDetail extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_complaint_detail);
TextView tvComplaintID = (TextView)findViewById(R.id.complaintid);
TextView tvTicketCat = (TextView)findViewById(R.id.TicketHeading);
TextView tvSubCat = (TextView)findViewById(R.id.Subheading);
//tvComplaintID.setText(MainActivity.StatusImg);
tvTicketCat.setText( MainActivity.TicketCat);
// tvSubCat.setText(MainActivity.SubCat);
final Button butt = findViewById(R.id.review);
butt.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(ComplaintDetail.this, Review.class);
startActivity(intent);
}
});
final Button button = findViewById(R.id.close);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Toast.makeText(ComplaintDetail.this, "This ticket is closed!!", Toast.LENGTH_SHORT).show();
}
});
}}
I want to display the children: ticketCategory, subcategory and status.
I will highly appreciate any help.
thank you!!
[EDIT]
public class Ticket {
String ticketCategory;
String name;
String complaintID;
String subcategory;
String priority;
String status;
private String comments;
private String cannedReply;
public Ticket(){}
public Ticket (String ticketCategory, String subcategory, String priority, String status, String comments, String cannedReply)
{
this.ticketCategory = ticketCategory;
// this.Name = Name;
this.subcategory = subcategory;
this.priority = priority;
this.status = status;
this.comments = comments;
this.cannedReply = cannedReply;
}
public void setTicketCategory(String ticketCategory) {
this.TicketCategory = ticketCategory;
}
public void setName(String name) {
this.Name = name;
}
public void setSubcategory(String subcategory) {
this.Subcategory = subcategory;
}
public void setPriority(String priority) {
this.priority = priority;
}*/
public void setStatus(String status) {
this.status = status;
}
public String getTicketCategory() {
return ticketCategory;
}
public String getSubcategory() {
return subcategory;
}
public String getPriority() {
return priority;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public String getCannedReply() {
return cannedReply;
}
public void setCannedReply(String cannedReply) {
this.cannedReply = cannedReply;
}
public String getStatus() {return status;}
public String getComplaintID() {
return complaintID;
}
public static ArrayList<Ticket> getTicket()
{
ArrayList<Ticket> tickets = new ArrayList<Ticket>();
return tickets;
}}
Just make your ticket class as serializable and pass it in bundel and parse in other activity like bellow
First change your Ticket class definition like bellow
public class Ticket implements Serializable {
Then after change your click code like bellow
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(view.getContext(), ComplaintDetail.class);
intent.putExtra("ticket", ticket);
startActivity(intent);
}
});
And finally parse and get your object in second activity like bellow
Ticket ticket= (Ticket) getIntent().getSerializableExtra("ticket");
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(view.getContext(), ComplaintDetail.class);
intent.putExtra("ticket", ticket);
startActivity(intent);
}
});
The object i mentioned ticket in intent is the object u receive from fireabse and you need make a object parceable to be able to send it to another activity.So, make sure sure to make it parceable.
The below is the model class with implementing parceable interface:-
public class Ticket implements Parcelable {
private String ticketCategory;
private String name;
private String complaintID;
private String subcategory;
private String priority;
private String status;
private String comments;
private String cannedReply;
public Ticket() {
}
public Ticket(String ticketCategory, String subcategory, String priority, String status, String comments, String cannedReply) {
this.ticketCategory = ticketCategory;
// this.Name = Name;
this.subcategory = subcategory;
this.priority = priority;
this.status = status;
this.comments = comments;
this.cannedReply = cannedReply;
}
public String getTicketCategory() {
return ticketCategory;
}
public void setTicketCategory(String ticketCategory) {
this.ticketCategory = ticketCategory;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getComplaintID() {
return complaintID;
}
public void setComplaintID(String complaintID) {
this.complaintID = complaintID;
}
public String getSubcategory() {
return subcategory;
}
public void setSubcategory(String subcategory) {
this.subcategory = subcategory;
}
public String getPriority() {
return priority;
}
public void setPriority(String priority) {
this.priority = priority;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public String getCannedReply() {
return cannedReply;
}
public void setCannedReply(String cannedReply) {
this.cannedReply = cannedReply;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.ticketCategory);
dest.writeString(this.name);
dest.writeString(this.complaintID);
dest.writeString(this.subcategory);
dest.writeString(this.priority);
dest.writeString(this.status);
dest.writeString(this.comments);
dest.writeString(this.cannedReply);
}
protected Ticket(Parcel in) {
this.ticketCategory = in.readString();
this.name = in.readString();
this.complaintID = in.readString();
this.subcategory = in.readString();
this.priority = in.readString();
this.status = in.readString();
this.comments = in.readString();
this.cannedReply = in.readString();
}
public static final Parcelable.Creator<Ticket> CREATOR = new Parcelable.Creator<Ticket>() {
#Override
public Ticket createFromParcel(Parcel source) {
return new Ticket(source);
}
#Override
public Ticket[] newArray(int size) {
return new Ticket[size];
}
};
}
So,I have the set and get methods and implemented the parceable i.e made the class parceable so that u can send the entire object.Now in other activity where you will be receiving,You can just use get methods like below
First get the intent through getIntent() in onCreate and declare the object Ticket.
ticket = getIntent().getParcelableExtra("Ticket");
And where you need the object there you can directly access it like below
ticket.getSubcategory();
ticket.getTicketCategory();
ticket.getStatus();
So,Thats it ask me if you didn't get any thing and if it is not working.

Populate the list view using specific data from the Firebase console

I need help with displaying data from the firebase console. So the scene is that I have put some data in the console using a seperate class called "TicketSubmitted". I need to display some of the children of the data in a list view in the "MainActivity". The model class for the MainActivity is called "Ticket" and the adapter for the list view is called "TicketAdapter"
the code for the MainActivity is:
package com.android.example.ithelpdesk;
//imports
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
DrawerLayout drawer;
ActionBarDrawerToggle toggle;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference mDatabaseReference;
private ChildEventListener mChildEventListener;
private FirebaseAuth mFirebaseAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
public TicketAdapter adapter;
private final static int RC_SIGN_IN = 2;
public String mUsername;
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mFirebaseAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
mDatabaseReference = FirebaseDatabase.getInstance().getReference();
FirebaseUser user = mFirebaseAuth.getCurrentUser();
mUsername = user.getUid();
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = mFirebaseAuth.getCurrentUser();
if (user != null) {
onSignedInInitialized(user.getDisplayName());
} else {
onSignedOutCleanup();
startActivityForResult(
getInstance()
.createSignInIntentBuilder()
.setIsSmartLockEnabled(false)
.setAvailableProviders(Arrays.asList(
new AuthUI.IdpConfig.EmailBuilder().build(),
new AuthUI.IdpConfig.GoogleBuilder().build()))
.build(),
RC_SIGN_IN);
}
}
};
final ListView listView = (ListView) findViewById(R.id.lvTicket);
final ArrayList<String> arrayOfTicket = new ArrayList<>()
mDatabaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
Ticket ticket = (Ticket)dataSnapshot.getValue(Ticket.class);
adapter.add(ticket);
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
}
);mDatabaseReference.
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FirebaseAuth.getInstance().signOut();
}
});
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(view.getContext(), ComplaintDetail.class);
startActivity(intent);
}
});
final Button button = (Button) findViewById(R.id.complaintbutton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, TicketCategory.class);
startActivity(intent);
}
}
);
}
#Override
protected void onPostCreate(Bundle savedInstanceState)
{
super.onPostCreate(savedInstanceState);
toggle.syncState();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId())
{
case R.id.action_settings:
{
AuthUI.getInstance().signOut(this);
return true;
}
default:
return super.onOptionsItemSelected(item);
}
}
private void detachDatabaseReadListener()
{
if(mChildEventListener != null)
{
mDatabaseReference.removeEventListener(mChildEventListener);
mChildEventListener = null;
}
}
#Override
protected void onResume()
{
super.onResume();
mFirebaseAuth.addAuthStateListener(mAuthStateListener);
}
#Override
protected void onPause()
{
super.onPause();
mFirebaseAuth.removeAuthStateListener(mAuthStateListener);
}
private void onSignedInInitialized(String username)
{
mUsername = username;
// attachDatabaseReadListener();
}
private void onSignedOutCleanup()
{
mUsername = null;
}
The model class Ticket:
public class Ticket {
public String TicketCategory;
// public String Name;
public String Subcategory;
public String priority;
private String status;
private String comments;
private String cannedReply;
public Ticket (String TicketCategory, String Subcategory, String priority, String status, String comments, String cannedReply)
{
this.TicketCategory = TicketCategory;
// this.Name = Name;
this.Subcategory = Subcategory;
this.priority = priority;
this.status = status;
this.comments = comments;
this.cannedReply = cannedReply;
}
public void setStatus(String status) {
this.status = status;
}
public String getTicketCategory() {
return TicketCategory;
}
//public String getName(){return Name;}
public String getSubcategory() {
return Subcategory;
}
public String getPriority() {
return priority;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public String getCannedReply() {
return cannedReply;
}
public void setCannedReply(String cannedReply) {
this.cannedReply = cannedReply;
}
public String getStatus() {
return status;
}
public static ArrayList<Ticket> getTicket()
{
ArrayList<Ticket> tickets = new ArrayList<Ticket>();
return tickets;
}}
The code for the adapter TicketAdapter is:
public class TicketAdapter extends ArrayAdapter<Ticket> {
TicketAdapter(Context context, ArrayList<Ticket> tickets) {
super(context, 0, tickets);
}
#SuppressLint("SetTextI18n")
#NonNull
#Override
public View getView(int position, View convertView, #NonNull ViewGroup parent) {
Ticket ticket = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.tickets, parent, false);
}
TextView tvCategory = (TextView) convertView.findViewById(R.id.TicketCategory);
TextView tvSubcategory = (TextView) convertView.findViewById(R.id.Subcategory);
TextView tvPriority = (TextView) convertView.findViewById(R.id.priority);
assert ticket != null;
tvCategory.setText(ticket.TicketCategory);
tvSubcategory.setText(ticket.Subcategory);
tvPriority.setText(ticket.priority);
return convertView;
}}
I just want to display the TicketCategory, Subcategory and priority in a set manner in the list view but i am unable to do so. Also when I introduce a new childEventListener, i get this error and the app crashes:
Screenshot
I am new at android programming so any input will be appreciated...
thanks!!
To solve this error:
com.google.firebase.database.DatabaseException: Found two getters or fields with conflicting case sensitivity for property: subcategory
Please change the following lines of code:
public String TicketCategory;
// public String Name;
public String Subcategory;
public String priority;
to
private String TicketCategory;
// private String Name;
private String Subcategory;
private String priority;
And don't forget to add the no-argument constructor in your Ticket class.
public Ticket() {} //Needed for Firebase
First your log say that you need to rename your Ticket fields like (can't start with an uppercase) :
public String ticketCategory;
public String subcategory;
Then you must instanciate your adapter with your arrayOfTicket and then set the adapter to your ListView (+ don't forget to call adapter.notifyDataSetChanged() when you add/remove object in your list) :
final ListView listView = (ListView) findViewById(R.id.lvTicket);
final ArrayList<Ticket> arrayOfTicket = new ArrayList<>();
adapter = new TicketAdapter(this, arrayOfTicket); // Instanciate your adapter
listView.setAdapter(adapter); // Set the adapter to your ListView
mDatabaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
Ticket ticket = (Ticket)dataSnapshot.getValue(Ticket.class);
adapter.add(ticket);
adapter.notifyDataSetChanged(); // Notify for changes to reload the list
}
...
I guess that your problem is in the way that you refer to the data, you don't seem to refer to the actual node that must list the data.
lets say your node that you save the data in is called Tickets
so instead of this:
mDatabaseReference.addChildEventListener(new ChildEventListener() {....
do this:
DatabaseReference tickets_ref = mDatabaseReference.child("Tickets");
tickets_ref.addChildEventListener(new ChildEventListener() {....
instead of this:
final ArrayList<String> arrayOfTicket = new ArrayList<>();
do this:
final ArrayList<Ticket> arrayOfTicket = new ArrayList<>();
now after this:
final ArrayList<Ticket> arrayOfTicket = new ArrayList<>();
initialize the adapter like this:
adapter = new TicketAdapter(context,arrayOfTicket);
and instead of this:
adapter.add(ticket);
do this:
arrayOfTicket.add(ticket);
adapter.notifyDataSetChanged();

Calling a class object for each item of recycler view android

There is a situation, I have an activity having recycler view and I have its adapter, there is a model class for three Text Views of a recycler view location,latitude,longitude that comes from database. Now I want the fourth field of recycler view the distance. distance is calculated by another class and return distance in a callback function. where do I initialize the object of that class in recyclerview so that it updates the distance continuously against the lat and long of each item.
Code that return distance for single lat,long
compassManager = new CompassManager(getApplicationContext(), this);
if (isLocationServiceEnabled()) {
Log.i("FloatingViewServie","Location Service Enabled");
// i want to pass latitude and longitude of UserLocations below to
// get distance on each row
compassManager.startNavigating(33.69206669, 73.03208828);
compassManager.getLocation().getLatitude();
compassManager.getLocation().getLongitude();
}
callback method that return continusly updated distance
#Override
public void onDistanceUpdate(float distance) {
//this distance need to be on recyclerview for each row
}
Recyclerview Adapter
public class ActiveLocationsAdapter extends RecyclerView.Adapter<ActiveLocationsAdapter.MyViewHolder> {
public interface OverflowOptions
{
public void edit(int position,UserLocations userLocations);
public void delete();
}
private List<UserLocations> userLocationsList;
FirebaseDatabase database;
DatabaseReference rootRef;
private FirebaseAuth mAuth;
FirebaseUser user;
Context context;
OverflowOptions overflowOptionsCallback;
public ActiveLocationsAdapter(Context context,List<UserLocations> locationsList,OverflowOptions callback) {
this.userLocationsList = locationsList;
database = FirebaseDatabase.getInstance();
rootRef = database.getReference();
mAuth = FirebaseAuth.getInstance();
user = mAuth.getCurrentUser();
this.context=context;
overflowOptionsCallback=callback;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.row_active_locations, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
// model class that have latitude and longitude for each row
final UserLocations userLocations = userLocationsList.get(position);
Log.i("aaposition",String.valueOf(holder.getAdapterPosition()));
holder.name.setText(userLocations.getName());
// holder.distance.setText(String.valueOf(userLocations.getLatitude()));
// holder.direction.setText(String.valueOf(userLocations.getLongitude()));
holder.overflow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//creating a popup menu
PopupMenu popup = new PopupMenu(context, holder.overflow);
//inflating menu from xml resource
popup.inflate(R.menu.locations_overflow_menu);
//adding click listener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_edit:
overflowOptionsCallback.edit(holder.getAdapterPosition(), userLocations);
break;
case R.id.action_delete:
break;
}
return false;
}
});
//displaying the popup
popup.show();
}
});
}
#Override
public int getItemCount() {
return userLocationsList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView name, distance, direction;
public ImageView overflow;
public MyViewHolder(View view) {
super(view);
name = (TextView) view.findViewById(R.id.name);
distance = (TextView) view.findViewById(R.id.distance);
direction = (TextView) view.findViewById(R.id.direction);
overflow = (ImageView) view.findViewById(R.id.overflow);
}
}
}
Model Class
public class UserLocations {
String id;
String name;
double latitude;
double longitude;
String status;
public UserLocations() {
}
public UserLocations(String id, String name, double latitude, double longitude, String status) {
this.id=id;
this.name = name;
this.latitude = latitude;
this.longitude = longitude;
this.status = status;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public String getStatus() {return status;}
public void setStatus(String status) {this.status = status;}
}
Row of Recyclerview
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="true"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:clickable="true"
android:background="?android:attr/selectableItemBackground"
android:orientation="vertical">
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:textColor="#color/heading"
android:textSize="16dp"
android:textStyle="bold" />
<TextView
android:id="#+id/distance_lable"
android:layout_below="#id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/subheading"
android:text="Distance : "/>
<!-- To display distance-->
<TextView
android:id="#+id/distance"
android:layout_below="#id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/subheading"
android:layout_toRightOf="#+id/distance_lable"
/>
<TextView
android:layout_below="#id/name"
android:id="#+id/direction_lable"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/distance"
android:textColor="#color/subheading"
android:text=" Direction : "/>
<!-- To display direction-->
<TextView
android:id="#+id/direction"
android:layout_below="#id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/subheading"
android:layout_toEndOf="#+id/direction_lable"/>
<ImageButton
android:id="#+id/overflow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginRight="5dp"
android:background="#drawable/ic_more_vert_black_24dp"
/>
</RelativeLayout>
Main Activity that have recyclerview
public class MainActivity extends AppCompatActivity
implements CurrentLocationManager.ResultSupplier,NavigationView.OnNavigationItemSelectedListener,ActiveLocationsAdapter.OverflowOptions{
private static final int CODE_DRAW_OVER_OTHER_APP_PERMISSION = 2084;
public static final int REQUEST_FINE_LOCATION = 1;
public static final String TAG= MainActivity.class.getSimpleName();
private PrefManager prefManager;
CurrentLocationManager currentLocationManager;;
private List<UserLocations> userLocationsList = new ArrayList<>();
private RecyclerView recyclerView;
private ActiveLocationsAdapter mAdapter;
FirebaseDatabase database;
DatabaseReference rootRef;
private FirebaseAuth mAuth;
FirebaseUser user;
ProgressDialog progressDoalog;
Context context,interfaceContext;
ImageButton imgBtnSaveLocation;
private double lattitude,longitude;
Switch toggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkPermissions(this);
permissionCheck();
context=getApplicationContext();
imgBtnSaveLocation=(ImageButton)findViewById(R.id.main_activity_save_btn) ;
progressDoalog = new ProgressDialog(MainActivity.this);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
toggle=(Switch)findViewById(R.id.active_locations_switch);
mAdapter = new ActiveLocationsAdapter(getApplicationContext(),userLocationsList,this);
prefManager = new PrefManager(this);
prefManager.setFirstTimeLaunch(false);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//database reference pointing to root of database
database = FirebaseDatabase.getInstance();
rootRef = database.getReference();
// gives current authenticated user
mAuth = FirebaseAuth.getInstance();
user = mAuth.getCurrentUser();
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
recyclerView.setAdapter(mAdapter);
progressDoalog.setMessage("Fetching Data. . .");
progressDoalog.show();
// get and update data on View on any change in database
rootRef.child(user.getDisplayName()).child("active_locations").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot noteDataSnapshot : dataSnapshot.getChildren()) {
UserLocations locations = noteDataSnapshot.getValue(UserLocations.class);
if(locations.getStatus().equals("active")) {
if (!contains((ArrayList<UserLocations>) userLocationsList, locations)) {
userLocationsList.add(locations);
}
}
}
mAdapter.notifyDataSetChanged();
progressDoalog.dismiss();
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
}
});
// button click that get current location and save to database
imgBtnSaveLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i(TAG,"onclick");
getLocation();
}
});
// turn the tracking on and off
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked)
Toast.makeText(context, "Toggle on", Toast.LENGTH_SHORT).show();
else
Toast.makeText(context, "Toggle off", Toast.LENGTH_SHORT).show();
}
});
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
public void permissionCheck()
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(getApplicationContext())) {
//If the draw over permission is not available open the settings screen
//to grant the permission.
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, CODE_DRAW_OVER_OTHER_APP_PERMISSION);
} else {
}
}
private void requestPermissions(Context context) {
ActivityCompat.requestPermissions((Activity) context,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION,android.Manifest.permission.ACCESS_COARSE_LOCATION},
REQUEST_FINE_LOCATION);
}
private boolean checkPermissions(Context context) {
if (ContextCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
requestPermissions(context);
return false;
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_active_locations) {
startActivity(new Intent(getApplicationContext(),ActiveLocationsActivity.class));
} else if (id == R.id.nav_tracked_locations) {
startActivity(new Intent(getApplicationContext(),TrackedLocationsActivity.class));
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
AuthUI.getInstance()
.signOut(this)
.addOnCompleteListener(new OnCompleteListener<Void>() {
public void onComplete(#NonNull Task<Void> task) {
// user is now signed out
startActivity(new Intent(getApplicationContext(), SignUpActivity.class));
finish(); }
});
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void getLocation()
{
currentLocationManager = new CurrentLocationManager(context,this);
currentLocationManager.getUpdatedLocation();
}
/**
* Compares two array list
* #param list
* #param locations
* #return
*/
boolean contains(ArrayList<UserLocations> list, UserLocations locations) {
for (UserLocations item : list) {
if (item.getId().equals(locations.getId())&&item.getName().equals(locations.getName())&&item.getLatitude()==locations.getLatitude()&&item.getLongitude()==locations.getLongitude()&&item.getStatus().equals(locations.getStatus())) {
return true;
}
}
return false;
}
#Override
public void result(double lat, double longi) {
lattitude=lat;
longitude=longi;
Log.i("callback result",String.valueOf(lat)+","+String.valueOf(longi));
}
#Override
public void edit(final int position, final UserLocations userLocations) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.dialog_edit_location_name, null);
dialogBuilder.setView(dialogView);
final EditText rename = (EditText) dialogView.findViewById(R.id.name);
dialogBuilder.setTitle("Rename Location");
//dialogBuilder.setMessage("hello");
dialogBuilder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
renameLocation(userLocations.getName(),rename.getText().toString());
userLocations.setName(rename.getText().toString());
userLocationsList.set(position, userLocations);
}
});
dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//pass
}
});
AlertDialog b = dialogBuilder.create();
b.show();
}
#Override
public void delete() {
}
public void renameLocation(final String name, final String renameLocation) {
Log.i("Interface","renameLocation");
Query renameQuery= rootRef.child(user.getDisplayName()).child("active_locations").orderByChild("name").equalTo(name);
renameQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
String child_name = (String) child.child("name").getValue();
if (child_name.equals(name)){
child.getRef().child("name").setValue(renameLocation);
Log.i("Rename Location","child renamed");
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}

Categories

Resources