How to implement search button to android Firebase database? - java

I tried so many time to implement to search my android Firebase database.
Query: query = dateRef.orderByChild("phone").equalTo(searchPhoneNumber);
I don't know how to set searchPhoneNumber in EditText value. But I know EditText and one button using to search phone numbers. But I need Java code. Eg: if I enter phone numbers in EditText and I press button, after I get a output in same page.
Here I attached my Firebase screenshot and my code.
Firebase database screenshot
java
public class ViewProduction extends AppCompatActivity {
private RecyclerView mRecyclerView;
private Adapater mAdapter;
private ProgressBar mprogress;
private DatabaseReference mDatabaseRef;
private List<Datastore> mUploads;
EditText edit;
Button btnsearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_production);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
edit =(EditText)findViewById(R.id.edit);
btnsearch = (Button)findViewById(R.id.btnsearch);
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("Production Details");
mRecyclerView = findViewById(R.id.recyclerj);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mprogress = findViewById(R.id.progress);
mUploads = new ArrayList<>();
mDatabaseRef = FirebaseDatabase.getInstance().getReference("Rajadriving");
btnsearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// called search() method on button click.
search();
}
});
public void search(){
edit.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference dateRef = rootRef.child("Rajadriving").child("9-6-2018");
Query query = dateRef.orderByChild("phone").equalTo(s.toString());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Datastore upload = postSnapshot.getValue(Datastore.class);
mUploads.add(upload);
}
mAdapter = new Adapater(ViewProduction.this, mUploads);
mRecyclerView.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
mprogress.setVisibility(View.INVISIBLE);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(ViewProduction.this, databaseError.getMessage(),Toast.LENGTH_SHORT).show();
mprogress.setVisibility(View.INVISIBLE);
}
});
}
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home){
this.finish();
}
return super.onOptionsItemSelected(item);
}
}
xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="com.udayaj.rajadriving.ViewProduction">
<EditText
android:id="#+id/edit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/progress"
android:layout_alignParentTop="true"
android:layout_alignRight="#+id/progress"
android:hint="enter phone" />
<Button
android:id="#+id/btnsearch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/recyclerj"
android:layout_marginLeft="21dp"
android:layout_marginStart="21dp"
android:layout_toEndOf="#+id/edit"
android:layout_toRightOf="#+id/edit"
android:text="Search" />
<ProgressBar
android:id="#+id/progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"/>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/table01"
android:scrollbars="vertical"
android:id="#+id/recyclerj">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>

I hope this will work for you.
Use Textwatcher() to implement search functionality.how to implement given below.
btnsearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// called search() method on button click.
search();
}
});
public void search(){
edit.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference dateRef = rootRef.child("Rajadriving").child("9-6-2018");
Query query = dateRef.orderByChild("phone").equalTo(s.toString());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Datastore upload = postSnapshot.getValue(Datastore.class);
mUploads.add(upload);
}
mAdapter = new Adapater(ViewProduction.this, mUploads);
mRecyclerView.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
mprogress.setVisibility(View.INVISIBLE);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(ViewProduction.this, databaseError.getMessage(),Toast.LENGTH_SHORT).show();
mprogress.setVisibility(View.INVISIBLE);
}
});
}
}
}

To solve this, please change the following line of code:
Query query = dateRef.orderByChild("phone").equalTo("searchPhoneNumber");
to
Query query = dateRef.orderByChild("phone").equalTo(searchPhoneNumber);
See, no quotation marks? You need to search the database after the value that your variable searchPhoneNumber holds and not after the searchPhoneNumber String which is obvious is not a phone number.

Related

Why is the spinner.setOnItemSelectedListener() not getting executed?

UPDATE:
I have found a work around that isn't necessarily the solution, but has solved my problem. To my interpretation, I think the use of online database causes a little delay or something that when the spinner.setOnItemSelectedListener() is set the list passed to the adapter is empty. So to counter that, I set the listener in the OnDataChange() method of firebase (which was fetching the data from database and creating the list). After that it worked fine.
Original Question
I have a simple spinner inside a layout in xml, and I have a query that creates a String type array of the items I want to show in the spinner. The list is being created and the spinner shows the items. But when I call the setOnItemSelectedListener() on it, it is not getting executed.
This is the xml:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Spinner
android:id="#+id/spinner_category_name_add_expense"
android:layout_width="wrap_content"
android:layout_height="24dp"
android:layout_alignParentEnd="true" />
</RelativeLayout>
There are more widgets around it, I don't know if that matters.
This is the java file:
public class AddExpense extends AppCompatActivity {
Spinner spinner_category_name_add_expense;
SharedPreferences sharedPreferences;
String userKey, userName, selected_cat;
DatabaseReference dbref;
ArrayList<String> categoryModelArrayList;
ArrayAdapter<String> spinnerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_expense);
fetchSharedPreferences();
categoryModelArrayList = new ArrayList<String>();
spinner_category_name_add_expense = findViewById(R.id.spinner_category_name_add_expense);
createCategoryList();
addCategoriesToSpinner();
spinner_category_name_add_expense.setOnItemSelectedListener(new
AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(AddExpense.this, "Selected", Toast.LENGTH_SHORT).show();
// not executing this
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
Toast.makeText(AddExpense.this, "Not Selected", Toast.LENGTH_SHORT).show();
// nor this
}
});
}
}
private void fetchSharedPreferences() {
sharedPreferences = this.getSharedPreferences("shared_prefs", Context.MODE_PRIVATE);
userKey = sharedPreferences.getString("user_key", null);
}
// gets the data from firebase database, works as the ArrayList is populated
public void createCategoryList() {
String currentUserCategoriesPath = "AssignmentUsers/" + userKey + "/userCategories";
dbref = FirebaseDatabase.getInstance().getReference(currentUserCategoriesPath);
dbref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
int i = 0;
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String categoryModel = snapshot.getKey();
categoryModelArrayList.add(categoryModel);
Log.d("firebase", String.valueOf(categoryModelArrayList.get(i)));
i++;
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("firebase", "Error");
}
});
}
public void addCategoriesToSpinner() {
spinnerAdapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_spinner_dropdown_item,
categoryModelArrayList
);
spinner_category_name_add_expense.setAdapter(spinnerAdapter);
spinnerAdapter.notifyDataSetChanged();
}
}

How do I implement the holder.itemView.setOnClickListener from the UserAdapter in a fragment?

I apologize about the title, I wasn't sure how to phrase my question correctly.
I have a UserAdapter, a Chatlist and a Searchfragment and the user_item. The problem is, the three Click Listeners "Follow", "Go to user's profile" and "Go to chatActivity" are available on both Fragments.
I want, that the "Go to user's profile" click listener only work in the Searchfragment but not in the Chatlistfragment and also hide the "follow/following" button on the Chatlistfragment. Right now they work on both fragments.
I'll appreciate any help!
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.ImageViewHolder> {
private Context mContext;
private List<User> mUsers;
private boolean isFragment;
private FirebaseUser firebaseUser;
String theLastMessage;
public UserAdapter(Context context, List<User> users, boolean isFragment) {
mContext = context;
mUsers = users;
this.isFragment = isFragment;
}
#NonNull
#Override
public UserAdapter.ImageViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.user_item, parent, false);
return new UserAdapter.ImageViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final UserAdapter.ImageViewHolder holder, final int position) {
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
final User user = mUsers.get(position);
holder.btn_follow.setVisibility(View.VISIBLE);
isFollowing(user.getId(), holder.btn_follow);
holder.username.setText(user.getUsername());
holder.fullname.setText(user.getFullname());
Glide.with(mContext).load(user.getImage()).into(holder.image_profile);
// Go to clicked user's profile
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (isFragment) {
SharedPreferences.Editor editor = mContext.getSharedPreferences("PREFS", MODE_PRIVATE).edit();
editor.putString("profileid", user.getId());
editor.apply();
((FragmentActivity) mContext).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new ProfileFragment()).commit();
} else {
Intent intent = new Intent(mContext, MainActivity.class);
intent.putExtra("publisherid", user.getId());
mContext.startActivity(intent);
}
}
});
// Start chatActivity with clicked user
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Intent intent = new Intent(mContext, MessageActivity.class);
intent.putExtra("userid", user.getId());
mContext.startActivity(intent);
return true;
}
});
// Click handler: User can un / follow by clicking on the button
holder.btn_follow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holder.btn_follow.getText().toString().equals("follow")) {
FirebaseDatabase.getInstance().getReference().child("Follow").child(firebaseUser.getUid())
.child("following").child(user.getId()).setValue(true);
FirebaseDatabase.getInstance().getReference().child("Follow").child(user.getId())
.child("followers").child(firebaseUser.getUid()).setValue(true);
addNotification(user.getId());
} else {
FirebaseDatabase.getInstance().getReference().child("Follow").child(firebaseUser.getUid())
.child("following").child(user.getId()).removeValue();
FirebaseDatabase.getInstance().getReference().child("Follow").child(user.getId())
.child("followers").child(firebaseUser.getUid()).removeValue();
}
}
});
}
// ViewHolder holding data of user
public class ImageViewHolder extends RecyclerView.ViewHolder {
public TextView username, fullname, last_message;
public CircleImageView image_profile;
public Button btn_follow;
public ImageViewHolder(View itemView) {
super(itemView);
username = itemView.findViewById(R.id.username);
fullname = itemView.findViewById(R.id.fullname);
image_profile = itemView.findViewById(R.id.image_profile);
btn_follow = itemView.findViewById(R.id.follow_btn);
last_message = itemView.findViewById(R.id.last_msg);
}
}
My SearchFragment
public class SearchFragment extends Fragment {
private RecyclerView recyclerView;
private UserAdapter userAdapter;
private List<User> userList;
EditText search_bar;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_search, container, false);
recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
search_bar = view.findViewById(R.id.search_bar);
userList = new ArrayList<>();
userAdapter = new UserAdapter(getContext(), userList, true);
recyclerView.setAdapter(userAdapter);
readUsers();
search_bar.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
searchUsers(charSequence.toString().toLowerCase());
}
#Override
public void afterTextChanged(Editable editable) {
}
});
return view;
}
private void searchUsers(String s){
Query query = FirebaseDatabase.getInstance().getReference("Users").orderByChild("username")
.startAt(s)
.endAt(s+"\uf8ff");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
userList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
User user = snapshot.getValue(User.class);
userList.add(user);
}
userAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void readUsers() {
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (search_bar.getText().toString().equals("")) {
userList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
User user = snapshot.getValue(User.class);
userList.add(user);
}
userAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
My ChatlistFragment
public class ChatListFragment extends Fragment {
private RecyclerView recyclerView;
private UserAdapter userAdapter;
private List<User> mUsers;
FirebaseUser fuser;
DatabaseReference reference;
private List<Chatlist> usersList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_chat_list, container, false);
// Init
recyclerView = view.findViewById(R.id.chatList_recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
fuser = FirebaseAuth.getInstance().getCurrentUser();
usersList = new ArrayList<>();
reference = FirebaseDatabase.getInstance().getReference("Chatlist").child(fuser.getUid());
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
usersList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Chatlist chatlist = snapshot.getValue(Chatlist.class);
usersList.add(chatlist);
}
chatList();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
return view;
}
private void chatList() {
mUsers = new ArrayList<>();
reference = FirebaseDatabase.getInstance().getReference("Users");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mUsers.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
User user = snapshot.getValue(User.class);
for (Chatlist chatlist : usersList) {
if (user.getId().equals(chatlist.getId())) {
mUsers.add(user);
}
}
}
userAdapter = new UserAdapter(getContext(), mUsers, true);
recyclerView.setAdapter(userAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
My User_item.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp">
<!-- Profile Picture -->
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/image_profile"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/profile" />
<!-- Layout: Username, fullname, last message -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_toEndOf="#+id/image_profile"
android:orientation="vertical">
<TextView
android:id="#+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxLines="1"
android:text="Benutzername"
android:textColor="#color/colorProfileFollowPostText"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:id="#+id/fullname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxLines="1"
android:text="Name"
android:textColor="#color/colorBlack" />
<TextView
android:id="#+id/last_msg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="12sp"
android:maxLines="1"
android:layout_marginEnd="10dp"
android:text="Last message" />
</LinearLayout>
<!-- Button: Follow -->
<Button
android:id="#+id/follow_btn"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_alignParentEnd="true"
android:layout_marginEnd="10dp"
android:background="#drawable/followbutton"
android:padding="5dp"
android:text="Folgen"
android:textColor="#color/colorProfileFollowPostText"
android:visibility="gone" />
</RelativeLayout>
Generally in this case, just having a boolean in the constructor of the adapter will do the job.
Let's say your isFragment boolean is used for this. So follow button visibility just set to GONE if isFragment is true and when clicking on "Go to user's profile" button just do this:
if (isFragment)
return
Hope that helps you.

Radio buttons inside AlertDialog saving to Firebase with different errors [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am working with an Uber clone tutorial and trying to set car type in a layout when updating driver info. Everything else works except the radio button part.
I tried the following but only got the following errors:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.RadioGroup.check(int)' on a null object reference
at DriverHome.showDialogUpdateInfo(DriverHome.java:783)
at DriverHome.onNavigationItemSelected(DriverHome.java:771)
layout_update_info
...
<RadioGroup
android:id="#+id/radioGroup"
android:orientation="horizontal"
android:layout_marginTop="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RadioButton
android:layout_marginRight="10dp"
android:id="#+id/RydeX"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="UberX"/>
<RadioButton
android:layout_marginRight="10dp"
android:id="#+id/RydeVan"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="UberBlack"/>
<RadioButton
android:id="#+id/RydeSUV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="UberXL"/>
</RadioGroup>
....
DriverHome.java
public class DriverHome extends AppCompatActivity {
private RadioGroup radioGroup;
String service;
private String userID;
private DatabaseReference driverDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_driver_home);
...
}
#RequiresApi(api = Build.VERSION_CODES.M)
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_update_info) {
showDialogUpdateInfo();
}
DrawerLayout drawer = (DrawerLayout)findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
private void showDialogUpdateInfo() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(DriverHome.this);
alertDialog.setTitle("UPDATE INFORMATION");
alertDialog.setMessage("Please fill in all information");
LayoutInflater inflater = this.getLayoutInflater();
View layout_pwd = inflater.inflate(R.layout.layout_update_info, null);
final MaterialEditText editName = (MaterialEditText)layout_pwd.findViewById(R.id.editName);
final MaterialEditText editPhone = (MaterialEditText)layout_pwd.findViewById(R.id.editPhone);
final ImageView image_upload = (ImageView) layout_pwd.findViewById(R.id.image_upload);
saveUserInfo();
image_upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
chooseImage();
}
});
alertDialog.setView(layout_pwd);
//Set Button
alertDialog.setPositiveButton("UPDATE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
final SpotsDialog waitingDialog = new SpotsDialog(DriverHome.this);
waitingDialog.show();
String name = editName.getText().toString();
String phone = editPhone.getText().toString();
Map<String, Object> updateInfo = new HashMap<>();
if (!TextUtils.isEmpty(name)) {
updateInfo.put("name", name);
}
if (!TextUtils.isEmpty(phone)) {
updateInfo.put("phone", phone);
}
// user_driver.tbl = "Users/Drivers"
DatabaseReference driverInformation = FirebaseDatabase
.getInstance().getReference(Common
.user_driver_tbl);
driverInformation.child(FirebaseAuth.getInstance()
.getCurrentUser().getUid())
.updateChildren(updateInfo)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(DriverHome.this,
"Information Updated!",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(DriverHome.this,
"Information Update Failed!",
Toast.LENGTH_SHORT).show();
}
waitingDialog.dismiss();
}
});
getUserInfo();
}
});
alertDialog.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
private void saveUserInfo() {
radioGroup = (RadioGroup)findViewById(R.id.radioGroup);
radioGroup.check(R.id.UberX);
int selectId = radioGroup.getCheckedRadioButtonId();
final RadioButton radioButton = (RadioButton)findViewById(selectId);
if (radioButton.getText() == null) {
return;
}
service = radioButton.getText().toString();
Map updateInfo = new HashMap();
updateInfo.put("service", service);
}
private void getUserInfo() {
driverDB.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists() && dataSnapshot.getChildrenCount()>0){
Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue();
if(map.get("service")!=null){
service = map.get("service").toString();
switch (service){
case"RydeX":
radioGroup.check(R.id.UberX);
break;
case"RydeVan":
radioGroup.check(R.id.UberBlack);
break;
case"RydeSUV":
radioGroup.check(R.id.UberXL);
break;
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
}
This is how it looks:
What I am trying to do is save the information to Firebase database:
name, phone, image and Type of Car the driver has.
Its simply a java.lang.NullPointerException
Problem
your RadioGroup is part of AlertDialog not DriverHome Activity. so the line below will return null.
radioGroup = (RadioGroup)findViewById(R.id.radioGroup);
Solution
You should get RadioGroup from its parent container which is AlertDialog. and do same for RadioButton although you can also get RadioButton from RadioGroup cause its the parent of all RadioButton.
radioGroup = (RadioGroup)layout_pwd.findViewById(R.id.radioGroup);

Android studio E/RecyclerView: No adapter attached; skipping layout

I have tried every solution I found on-line and anywhere. But I still can't solve this problem. It keeps giving me this error "E/RecyclerView: No adapter attached; skipping layout". I tried to use breakpoint to test each code. From the result, I get that data is successfully retrieved from firebase and save in ArrayList and the size of mItems is correct. But this is the result I get.Please somebody help me.
The Result I get
My firebase structure
ShowBookedSlotActivity.java
public class ShowBookedSlotActivity extends AppCompatActivity {
private static final String TAG ="Show Booked Activity" ;
private FirebaseAuth.AuthStateListener authListener;
private FirebaseAuth auth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_booked_slot);
setTitle("Booked Gym Slot");
Log.d(TAG, "on create");
//Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
//getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// getSupportActionBar().setHomeButtonEnabled(true);
auth = FirebaseAuth.getInstance();
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragmentContainer);
if (fragment == null) {
fragment = new ListBookedSlotFragment();
Bundle bundle = new Bundle();
bundle.putString("UID", auth.getCurrentUser().getUid());
fragment.setArguments(bundle);
fm.beginTransaction()
.add(R.id.fragmentContainer, fragment)
.commit();
}
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
#Override
public void onBackPressed()
{
super.onBackPressed();
startActivity(new Intent(ShowBookedSlotActivity.this, UserHomeActivity.class));
finish();
}
}
ListBookedSlotFragment.java
public class ListBookedSlotFragment extends Fragment {
private final String TAG = "ListBookedSlotFragment";
private ArrayList<BookedSlot> mItems;
private ArrayList<String> mItemsKey;
private RecyclerView mItemRecyclerView;
private ItemAdapter mAdapter;
private DatabaseReference mItemRef;
private DatabaseReference mDatabase;
private String UID;
private Query mBookedSlotQuery;
private DatabaseReference mBookedSlotRef;
private ValueEventListener mBookedSlotQueryVEL;
#SuppressLint("LongLogTag")
#Override
public void onCreate(Bundle savedInstanceState) {
UID = this.getArguments().getString("UID");
Log.d(TAG, "UID: " + UID);
mDatabase = FirebaseDatabase.getInstance().getReference();
mItems = new ArrayList<>();
if (UID != null) {
mItemsKey = new ArrayList<>();
mBookedSlotQuery = mDatabase.child("booked_slot").orderByChild("UserID").equalTo(UID);
Log.d(TAG, "mItemRef:" + mBookedSlotQuery);
mBookedSlotQueryVEL = mBookedSlotQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mItems.clear();
mItemsKey.clear();
Log.d(TAG, "onDataChange");
for (DataSnapshot d : dataSnapshot.getChildren()) {
BookedSlot bookedSlot = d.getValue(BookedSlot.class);
Log.d(TAG, "bookedSlot:" + bookedSlot.getUserID());
mItems.add(bookedSlot);
mItemsKey.add(d.getKey());
}
updateUI();
/* TextView infoTextTextview = (TextView) getActivity().findViewById(R.id.info_text); //show_booked_slot.xml
if (mItems.isEmpty()) {
infoTextTextview.setText(R.string.Empty);
} else {
// infoTextTextview.setVisibility(View.GONE);
infoTextTextview.setText("Size: ".concat(Integer.toString(mItems.size())));
}*/
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, "show booked slot databaseError: " + databaseError);
}
});
}
else{
Log.d(TAG, "UID: "+UID);
}
super.onCreate(savedInstanceState);
}
#Override
public void onDestroy() {
super.onDestroy();
// if (mBookedSlotQuery != null) mBookedSlotRef.removeEventListener(mBookedSlotQueryVEL);
}
#Override
public void onDetach() {
super.onDetach();
// if (mBookedSlotQuery != null) mBookedSlotRef.removeEventListener(mBookedSlotQueryVEL);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_list_booked_slot, container, false);
mItemRecyclerView = (RecyclerView) view.findViewById(R.id.item_recycler_view); //in fragment_list_item_booked_slot.xml
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(mItemRecyclerView.getContext(), new LinearLayoutManager(getActivity()).getOrientation());
mItemRecyclerView.addItemDecoration(dividerItemDecoration);
mItemRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return view;
}
private void updateUI() {
Log.d(TAG, "Enter updateUI(); mItems: " + mItems);
mAdapter = new ItemAdapter(mItems);
mItemRecyclerView.setAdapter(mAdapter);
}
private class ItemHolder extends RecyclerView.ViewHolder {
BookedSlot mItems;
TextView mNameTextView;
TextView mDateTextView;
TextView mTimeTextView;
ItemHolder(final View itemView) {
super(itemView);
//refer list_booked_gym_slot.xml
mNameTextView = (TextView) itemView.findViewById(R.id.textview_name);
mDateTextView = (TextView) itemView.findViewById(R.id.textview_date);
mTimeTextView = (TextView) itemView.findViewById(R.id.textview_time);
if (UID != null) {
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "UID != null");
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder
.setMessage("Delete This Slot?")
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
deleteSlot(mItems);
}
}).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
});
}
}
void bindData(BookedSlot s){
mItems = s;
mNameTextView.setText(s.getUsername());
mDateTextView.setText(s.getBookedDate());
mTimeTextView.setText(s.getBookedTime());
}
}
private class ItemAdapter extends RecyclerView.Adapter<ItemHolder>{
private ArrayList<BookedSlot> mItems;
ItemAdapter(ArrayList<BookedSlot> Items){
this.mItems = Items;
}
#Override
public ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
View view = layoutInflater.inflate(R.layout.list_booked_gym_slot,parent,false);
return new ItemHolder(view);
}
#Override
public void onBindViewHolder(ItemHolder holder, int position) {
BookedSlot s = mItems.get(position);
holder.bindData(s);
}
#Override
public int getItemCount() {
return mItems.size();
}
}
private void deleteSlot(final BookedSlot itemClicked) {
mDatabase.child("booked_slot").child(UID).child(mItemsKey.get(mItems.indexOf(itemClicked))).removeValue(new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if(databaseError == null){
Toast.makeText(getActivity(), itemClicked.getBookedDate() + " " + itemClicked.getBookedTime() +" Slot Deleted", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getActivity(), "Something went wrong. Please try again later.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
ShowBookedSlotActivity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.jaseline.myfyp.ShowBookedSlotActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.design.widget.AppBarLayout>
<TextView
android:id="#+id/info_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:textSize="18sp" />
<RelativeLayout
android:id="#+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.jaseline.myfyp.ShowBookedSlotActivity"
tools:showIn="#layout/activity_show_booked_slot">
</RelativeLayout>
</LinearLayout>
fragment_list_booked_slot.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/item_recycler_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scrollbars="vertical">
</android.support.v7.widget.RecyclerView>
list_booked_slot.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:layout_marginStart="10dp"
android:orientation="vertical">
<TextView
android:id="#+id/textview_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:id="#+id/textview_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14sp" />
<TextView
android:id="#+id/textview_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14sp" />
</LinearLayout>
</RelativeLayout>
The Fragment Life Cycle is as follows :
1. constructor
2. onAttach
3. onCreate
4. onCreateView
So you cant call updateUI() method to set data to RecyclerView before setting LayoutManager.
Only after setting LayoutManager should you give data to RecyclerView

all fragments are loading at time of activity

I am very...very new to android development and I am trying to recreate a hybrid app I built in ionic, but do it in actual android.
I am having an issue with either layouts or fragment loading that I can't figure out.
What I want is something similar to the IG layout, where there is a bar at the bottom for navigation, clicking the button would load the new page. From my understanding the best way to accomplish that is to use a main activity, then each of the tabs at the bottom are fragments.
So I built that, but I want the top toolbar to disappear on the second tab, so in the second tab "onCreateView" method I added the toolbar.setVisibility(View.GONE); however, as soon as I load the app, even on the first tab, the toolbar at the top is gone, signifying it is loading the views for each fragment when the app loads. I would think that would severely impact performance on a large app. Am I crazy?
Here is my main layout for the main activity...
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/main_layout">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="#color/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<android.support.v4.view.ViewPager
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar" />
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
android:gravity="center_horizontal"
android:layout_gravity="center_horizontal"
android:background="?attr/colorPrimary"
android:elevation="6dp"
app:tabSelectedTextColor="#FFFFFF"
app:tabTextColor="#D3D3D3"
app:tabIndicatorColor="#FF00FF"
android:minHeight="?attr/actionBarSize"
android:layout_alignParentBottom="true" />
</RelativeLayout>
Then my HomeActivity class..
public class HomeActivity extends BaseActivity implements OnFragmentTouched {
private TextView mTextMessage;
private static final String SELECTED_ITEM = "arg_selected_item";
private int mSelectedItem;
private BottomNavigationView mBottomNav;
private FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putInt(SELECTED_ITEM, mSelectedItem);
super.onSaveInstanceState(outState);
}
#Override
public void onBackPressed() {
MenuItem homeItem = mBottomNav.getMenu().getItem(0);
if (mSelectedItem != homeItem.getItemId()) {
// select home item
selectFragment(homeItem);
} else {
super.onBackPressed();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
ViewPager pager = (ViewPager) findViewById(R.id.content);
PagerAdapter pagerAdapter = (PagerAdapter) new PagerAdapter(getSupportFragmentManager(), HomeActivity.this);
pager.setAdapter(pagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(pager);
for(int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
tab.setCustomView(pagerAdapter.getTabView(i));
}
}
private void selectFragment(MenuItem item) {
Fragment frag = null;
switch(item.getItemId()) {
case R.id.navigation_home:
frag = new AllPostsFragment();
break;
case R.id.navigation_dashboard:
frag = ProfileFragment.newInstance(user.getUid());
break;
case R.id.navigation_notifications:
frag = new ChatListFragment();
break;
}
mSelectedItem = item.getItemId();
}
#VisibleForTesting
public ProgressDialog mProgressDialog;
public void showProgressDialog() {
if (mProgressDialog == null) {
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage(getString(R.string.loading));
mProgressDialog.setIndeterminate(true);
}
mProgressDialog.show();
}
public void hideProgressDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
#Override
public void onStop() {
super.onStop();
hideProgressDialog();
}
#Override
public void onFragmentTouched(Fragment fragment, float x, float y) {
Log.d("FRAGMENT_TOUCHED", "The ChatListFragment touch happened");
if(fragment instanceof ChatFragment) {
final ChatFragment theFragment = (ChatFragment) fragment;
Animator unreveal = theFragment.prepareUnrevealAnimator(x, y);
unreveal.addListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
}
#Override
public void onAnimationEnd(Animator animation) {
getSupportFragmentManager().beginTransaction().remove(theFragment).commit();
getSupportFragmentManager().executePendingTransactions();
}
#Override
public void onAnimationCancel(Animator animation) {}
#Override
public void onAnimationRepeat(Animator animation) {}
});
unreveal.start();
}
}
public String getUid() {
return FirebaseAuth.getInstance().getCurrentUser().getUid();
}
private class PagerAdapter extends FragmentPagerAdapter {
Context context;
String tabTitles[] = new String[] {"Home", "Profile", "Chat"};
public PagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public Fragment getItem(int pos) {
switch(pos) {
case 0: return new AllPostsFragment();
case 1: return ProfileFragment.newInstance(user.getUid());
case 2: return new ChatListFragment();
default:
return new AllPostsFragment();
}
}
#Override
public int getCount() {
return tabTitles.length;
}
#Override
public CharSequence getPageTitle(int position) {
return tabTitles[position];
}
public View getTabView(int position) {
View tab = LayoutInflater.from(HomeActivity.this).inflate(R.layout.custom_tab, null);
TextView tv = (TextView) tab.findViewById(R.id.custom_text);
tv.setText(tabTitles[position]);
return tab;
}
}
}
So, in the "ProfileFragment" in the onCreateView method I have...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_profile, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.userPostsRecycler);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getContext(), 2);
recyclerView.setLayoutManager(layoutManager);
Toolbar toolbar = getActivity().findViewById(R.id.toolbar);
toolbar.setVisibility(View.GONE);
followingCountText = rootView.findViewById(R.id.following_count);
followersCountText = rootView.findViewById(R.id.followers_count);
titleLayout = rootView.findViewById(R.id.toolbar_layout);
titleLayout.setTitle(user.getDisplayName());
fab1Container = rootView.findViewById(R.id.fab_1);
fab2Container = rootView.findViewById(R.id.fab_2);
ImageView profilePhoto = (ImageView) rootView.findViewById(R.id.profile_photo);
Glide.with(this).load(user.getPhotoUrl()).into(profilePhoto);
fabContainer = (LinearLayout) rootView.findViewById(R.id.fabContainerLayout);
fab = (FloatingActionButton) rootView.findViewById(R.id.profile_fab);
instigatingFab = fab;
fabBaseX = fab.getX();
fabBaseY = fab.getY();
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showBlurredDialog();
}
});
progressDialog = new ProgressDialog(getContext());
uploads = new ArrayList<>();
progressDialog.setMessage("Please wait...");
progressDialog.show();
DatabaseReference followersDB = FirebaseDatabase
.getInstance()
.getReference("followers")
.child(user.getUid())
.child("count");
followersDB.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int followersCount = dataSnapshot.getValue(Integer.class);
followersCountText.setText(Integer.toString(followersCount));
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
DatabaseReference followingReference = FirebaseDatabase.getInstance().getReference("following").child(user.getUid()).child("users");
followingReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
DatabaseReference followingDB = FirebaseDatabase.getInstance().getReference("following").child(user.getUid()).child("count");
followingDB.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int followingCount = dataSnapshot.getValue(Integer.class);
followingCountText.setText(Integer.toString(followingCount));
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mDatabase = FirebaseDatabase.getInstance().getReference("/userPosts").child(user.getUid()).child("posts");
mDatabase.limitToFirst(25).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
progressDialog.dismiss();
for(DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
String postID = postSnapshot.getKey();
uploads.add(postID);
}
uploads.add("-KtvzkOL_75wiKA4CMsr");
adapter = new ProfileUserPostsViewHolder(getContext(), uploads);
recyclerView.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
progressDialog.dismiss();
}
});
return rootView;
}
As you can see I am setting the visibility for the toolbar from the HomeActivity to View.GONE, however, the toolbar is gone from all fragments now. I just want a bottom navigation setup with a top toolbar that can be hidden when certain fragments load, but is visible in other fragments. Is that even possible? Thank you.
You can control the numbers of fragments loading in view pager by simply using this method:
viewPager.setOffscreenPageLimit(1); // where n is the number of offscreen pages you want to load.
you can increase or decrease the number of fragments loading according to your requirements but atleast 1.
hope this will help you.

Categories