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

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

Related

androidstudio recyclerview and custom dialog

I want to create a custom dialog with a recycler view on it. If I choose the recycler view cell and press ok button in dialog, then the textview will change. I created recycler view adapter, custom dialog, but I don't know how to connect dialog and adapter and what to put in onClick function..help me please..
custom_dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:id="#+id/writing_dialog"
android:layout_width="match_parent"
android:layout_height="400dp">
<TextView
android:id="#+id/textView8"
android:layout_width="0dp"
android:layout_height="50dp"
android:fontFamily="#font/nexon"
android:text="choose!"
android:textAlignment="center"
android:gravity="center"
android:textColor="#341867"
android:textSize="20dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/writing_dialog_ok"
android:layout_width="65dp"
android:layout_height="39dp"
android:layout_marginEnd="20dp"
android:background="#00FFFFFF"
android:fontFamily="#font/nexon"
android:text="ok"
android:textColor="#341867"
android:textSize="15dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="#+id/guideline6" />
<Button
android:id="#+id/writing_dialog_cancel"
android:layout_width="65dp"
android:layout_height="39dp"
android:layout_marginEnd="30dp"
android:background="#00FFFFFF"
android:text="cancel"
android:textColor="#341867"
android:textSize="15dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/writing_dialog_ok"
app:layout_constraintTop_toTopOf="#+id/guideline6" />
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_begin="355dp" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/writing_dialog_recy"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="20dp"
app:layout_constraintBottom_toTopOf="#+id/guideline6"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView8" />
</androidx.constraintlayout.widget.ConstraintLayout>
recyclerview cell
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:id="#+id/dialog_container"
android:layout_width="match_parent"
android:layout_height="45dp">
<RadioButton
android:id="#+id/dialog_radio"
android:layout_width="0dp"
android:layout_height="45dp"
android:fontFamily="#font/nexon"
android:text="시리즈 1"
android:textSize="18dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
recycler view adapter
public class WritingNovelAdapter extends RecyclerView.Adapter<WritingNovelAdapter.Holder>{
private Context context;
private ArrayList<WritingNovel_data> dataList;
public WritingNovelAdapter(Context context, ArrayList<WritingNovel_data> dataList){
this.context = context;
this.dataList = dataList;
}
public static class Holder extends RecyclerView.ViewHolder{
protected ConstraintLayout dialog_container;
protected RadioButton dialog_radio;
public Holder(View view){
super(view);
this.dialog_container = view.findViewById(R.id.dialog_container);
this.dialog_radio = view.findViewById(R.id.dialog_radio);
}
}
#Override
public WritingNovelAdapter.Holder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.writing_dialog_cell, parent, false);
Holder holder = new WritingNovelAdapter.Holder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull WritingNovelAdapter.Holder holder, final int position) {
String title = dataList.get(position).title;
if(title.length() > 16){
title = title.substring(0, 15) + "…";
}
holder.dialog_radio.setText(title);
holder.dialog_container.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
//????????????????????????????
}
});
}
#Override
public int getItemCount() {
if(dataList == null){
return 0;
}
else{
return dataList.size();
}
}
}
custom dialog class
class CustomDialog {
private Context context;
public CustomDialog(Context context)
{
this.context = context;
}
public void callDialog()
{
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.writing_novel_series_dialog);
dialog.show();
final RecyclerView writing_dialog_recy = dialog.findViewById(R.id.writing_dialog_recy);
final Button writing_dialog_ok = dialog.findViewById(R.id.writing_dialog_ok);
final Button writing_dialog_cancel = dialog.findViewById(R.id.writing_dialog_cancel);
writing_dialog_ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
writing_dialog_cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
}
====EDIT-1====
I call my dialog in here!
public class writing_novel extends AppCompatActivity {
private static final int GALLERY_REQUEST = 979;
private RichEditor mEditor;
private ColorPicker colorPicker;
androidx.appcompat.app.AlertDialog.Builder textSizeDialogBuilder;
private NumberPicker textPicker;
androidx.appcompat.app.AlertDialog.Builder youtubeDialogBuilder;
private EditText etYoutubeUrl;
private Button writing_novel_btn_series;
private ImageButton writing_novel_novel_ibtn_next;
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:{
finish();
return true;
}
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_writing_novel);
Toolbar toolbar = findViewById(R.id.writing_novel_main_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
writing_novel_novel_ibtn_next = findViewById(R.id.writing_novel_novel_ibtn_next);
writing_novel_novel_ibtn_next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(writing_novel.this);
builder.setTitle("정말 다음으로 넘어가시겠습니까?").setMessage("다음으로 넘어가기전, 한번 더 검토해주세요.");
builder.setPositiveButton("넘어가기", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int id)
{
Toast.makeText(getApplicationContext(), "OK Click", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(writing_novel.this, decide_novel_title.class);
startActivity(intent);
}
});
builder.setNegativeButton("취소", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int id)
{
Toast.makeText(getApplicationContext(), "Cancel Click", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
builder.setCancelable(false);
builder.create().show();
}
});
writing_novel_btn_series = findViewById(R.id.writing_novel_btn_series);
writing_novel_btn_series.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bundle args = new Bundle();
args.putString("id", "");
DialogFragment dialogFragment = new DialogFragment();
dialogFragment.setArguments(args);
dialogFragment.show(getFragmentManager(), "id");
CustomDialog dialog = new CustomDialog(writing_novel.this);
dialog.show(getSupportFragmentManager(), "CustomDialog");
}
});
If I understand correctly, you are trying to figure out how to display the RecyclerView list of items, and when an item is clicked, show its data in a TextView below. Please correct me if I am wrong.
For the first step, you are close. All you need to do is instantiate a new layout manager and an instance of your adapter class, and pass them to your RecyclerView.
Add this to your CustomDialog class:
public void callDialog() {
...
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(context);
writing_dialog_recy.setLayoutManager(layoutManager);
// I'm assumming you are passing a list of data here
WritingNovelAdapter adapter = new WritingNovelAdapter(context, dataList);
writing_dialog_recy.setAdapter(adapter);
...
As for showing the text in the textView, you have a few different ways to implement this. Its hard to say without seeing the rest of the related code, but I would recommend implementing a callback interface and calling the method from your ViewHolder, like so:
Define the interface in your Adapter class
public interface CallbackInterface {
void showText(String text);
}
Implement a callback interface in your CustomDialog class and implement the setText method, which is where you will set the text in the TextView. This will require that you have an instance of the TextView that you want to show that text in, meaning you must call this somewhere: TextView textView = findViewById(R.id.textView8);
class CustomDialog implements CallbackInterface {
...
public void showText(String text) {
textView.setText(text);
}
}
Pass an instance of your CustomDialog to the adapter (make sure to redefine adapter constructor to accept an instance of CustomDialog
public void callDialog() {
...
// I'm assumming you are passing a list of data here
WritingNovelAdapter adapter = new WritingNovelAdapter(context, dataList, this);
writing_dialog_recy.setAdapter(adapter);
...
}
Call the callback method from the adapter class when the recyclerview cell is clicked
public class WritingNovelAdapter extends RecyclerView.Adapter<WritingNovelAdapter.Holder> {
private Context context;
private ArrayList<WritingNovel_data> dataList;
private CallbackInterface callbackInterface;
public WritingNovelAdapter(Context context, ArrayList<WritingNovel_data>
dataList, CallbackInterface callbackInterface){
this.context = context;
this.dataList = dataList;
this.callbackInterface = callbackInterface;
}
...
holder.dialog_container.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
callbackInterface.showText(title);
}
});
}
Edit #1
Your comment stated that your dialog is not showing up. Unless you left some code out of your CustomDialog class, this is because all your CustomDialog class is, is a Java class. You need to extend a superclass such as AlertDialog or DialogFragment. I'll do my best to summarize how to do this, but you should take a look at the android docs -> https://developer.android.com/guide/topics/ui/dialogs
Here is an example of a DialogFragment you could try creating:
public class CustomDialog extends DialogFragment implements CallbackInterface {
private Context context;
private TextView textView;
private RecyclerView writing_dialog_recy;
public CustomDialog(Context context) {
this.context = context;
}
/* This is the method which builds and essentially shows the dialog */
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
LayoutInflater inflater = getActivity().getLayoutInflater();
// Inflate your view that contains the recyclerview
View view = inflater.inflate(R.layout.custom_dialog);
// Your text view where you want to show the text after an item is clicked
textView = view.findViewById(R.id.textView8);
// Your recyclerview in your custom_dialog.xml
writing_dialog_recy = view.findViewById(R.id.writing_dialog_recy);
// Create the layout manager
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(context);
writing_dialog_recy.setLayoutManager(layoutManager);
// Create and set the adapter
WritingNovelAdapter adapter = new WritingNovelAdapter(context, dataList, this);
writing_dialog_recy.setAdapter(adapter);
builder.setView(view);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// do whatever you want when user clicks the positive button
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return builder.create(); // return the dialog builder
}
public void showText(String text) {
textView.setText(text);
}
}
Then in whatever activity you are creating this dialog from, you show the DialogFragment and pass it the activity's FragmentManager and a tag
CustomDialog dialog = new CustomDialog(this);
dialog.show(getSupportFragmentManager(), "CustomDialog");

Recyclerview updates when I click EditText and removes typo input

So when I click my EditText field called Search, I get the keyboard, and for a brief second I see the vatical line you see when you are typing. But then the recyclerview is updated, and the typo input is removed, and the keyboard is still showing, but when I type nothing happens, until I click on the EditText field a second time. How can this be??
This is my Fragment where I have the Recyclerview & EditText
public class FragmentST extends Fragment {
private final static String TAG = FragmentST.class.getSimpleName();
private FloatingActionButton addP, searchP;
private FirebaseFirestore firestore;
String editName, editNumber;
EditText textN, textID, searchText;
//https://www.youtube.com/watch?v=b_tz8kbFUsU&ab_channel=TVACStudio
public RecyclerView mResultList;
public FirestoreRecyclerAdapter adapter;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_st, container, false);
firestore = FirebaseFirestore.getInstance();
addP = (FloatingActionButton) view.findViewById(R.id.addP);
searchP = (FloatingActionButton) view.findViewById(R.id.searchP);
mResultList = (RecyclerView) view.findViewById(R.id.patientResults);
searchText = (EditText) view.findViewById(R.id.search_field);
setPatientView();
addPatientOnClick();
search();
return view;
}
private class PViewHolder extends RecyclerView.ViewHolder {
private TextView List_name, List_cpr;
private ImageView icon;
public PViewHolder(#NonNull View itemView) {
super(itemView);
List_name = itemView.findViewById(R.id.Pname);
List_cpr = itemView.findViewById(R.id.Pcpr);
icon = itemView.findViewById(R.id.pb);
}
}
private void setPatientView() {
//Query -->https://www.youtube.com/watch?v=cBwaJYocb9I&ab_channel=TVACStudio
Query query = firestore.collection("patients");
Log.d(TAG, "setPatientView: " + query);
//RecyclerOptions
FirestoreRecyclerOptions<users> options = new FirestoreRecyclerOptions.Builder<users>()
.setQuery(query, users.class)
.build();
adapter = new FirestoreRecyclerAdapter<users, PViewHolder>(options) {
#NonNull
#Override
public PViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view1 = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_patients_layout, parent, false);
return new PViewHolder(view1);
}
#Override
protected void onBindViewHolder(#NonNull PViewHolder holder, int position, #NonNull users model) {
holder.List_name.setText(model.getName());
holder.List_cpr.setText("CPR: " + model.getCpr());
System.out.println("last character: " + model.getCpr().substring(model.getCpr().length() - 1));
if ((Integer.parseInt(model.getCpr().substring(model.getCpr().length() - 1)) % 2) == 0) {
// number is even
int id = getResources().getIdentifier("com.example.wrd:drawable/female", null, null);
holder.icon.setImageResource(id);
} else {
// number is odd
int id = getResources().getIdentifier("com.example.wrd:drawable/male", null, null);
holder.icon.setImageResource(id);
}
}
};
mResultList.setHasFixedSize(true);
mResultList.setLayoutManager(new LinearLayoutManager(getActivity()));
mResultList.setAdapter(adapter);
}
private void search() {
searchP.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "HELLO "+searchText.getText().toString(), Toast.LENGTH_SHORT).show();
}
});
}
private void addPatientOnClick() {
addP.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "Button Clicked", Toast.LENGTH_SHORT).show();
//https://stackoverflow.com/questions/23669296/create-a-alertdialog-in-android-with-custom-xml-view
// custom dialog
final Dialog dialog = new Dialog(getActivity(), android.R.style.Theme_Material_Light_NoActionBar_Fullscreen);
dialog.setContentView(R.layout.fragment_add_patient);
dialog.setTitle("Add patient");
// set the custom dialog components - text, button
TextView text = (TextView) dialog.findViewById(R.id.text);
text.setText("Name");
TextView text2 = (TextView) dialog.findViewById(R.id.text2);
text2.setText("ID");
Button dialogButtonOk = (Button) dialog.findViewById(R.id.dialogButtonOK);
Button dialogButtonCancel = (Button) dialog.findViewById(R.id.dialogButtonCancel);
// if button is clicked, close the custom dialog
dialogButtonOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textN = (EditText) dialog.findViewById(R.id.editName);
textID = (EditText) dialog.findViewById(R.id.editNumber);
editName = textN.getText().toString();
editNumber = textID.getText().toString();
editNumber.length();
if (editNumber != null && editNumber.length() > 9) {
Log.d(TAG, "dialog: \ncpr: " + editNumber);
} else {
return;
}
if (editName.matches("")) {
return;
} else {
Log.d(TAG, "dialog: \n Name: " + editName);
}
DocumentReference documentReference = firestore.collection("patients").document(editNumber);
Map<String, Object> patient = new HashMap<>();
patient.put("name", editName);
patient.put("cpr", editNumber);
documentReference.set(patient).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
dialog.dismiss();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
});
dialogButtonCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
});
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onResume() {
super.onResume();
}
}
In the XML the EditText is set to the following
<EditText
android:id="#+id/search_field"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginLeft="15dp"
android:layout_marginEnd="10dp"
android:layout_marginRight="10dp"
android:background="#drawable/search_layout"
android:ems="10"
android:hint="Search"
android:inputType="textPersonName"
android:paddingLeft="20dp"
android:paddingTop="10dp"
android:paddingRight="20dp"
android:paddingBottom="10dp"
android:textSize="16sp"
android:layout_weight="1"
app:layout_constraintBottom_toBottomOf="#+id/searchP"
app:layout_constraintEnd_toStartOf="#+id/searchP"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/searchP" />

How to implement search button to android Firebase database?

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.

SetText from a Class to the main XML file

I'm trying to use the .setText within a java class to try to change the value of a TextView on the activity_main XML file, so far i'm getting the NullpointerExeption error and I've read that its due an error when declaring my variable. How can i achieve this? Do i need to declare it first at the mainActivity.java?
On my activity_main.xml i have a button -> it opens a custom listView -> if you press the 2 item on the list view -> it opens a custom alert dialog -> the custom alert dialog it contains 2 buttons -> if you press the second button -> it has to set the text of a TextView that is on activity_main.xml
Any help is appreciated!
MainActivity.java
final TextView KMLabel = (TextView)findViewById(R.id.KMlabel);
activity.main.xml
<TextView
android:id="#+id/KMlabel"
android:layout_alignBottom="#+id/TVKm"
android:layout_toRightOf="#+id/TVKm"
android:textSize="22sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#e6c009"
android:text="KM/H"
android:textStyle="italic"/>
custom.java
public class custom extends BaseAdapter{
Context context;
String Item[];
String SubItem[];
int flags[];
LayoutInflater inflter;
public custom(Context applicationContext, String[] Item, String[] SubItem , int[] flags) {
this.context = context;
this.Item = Item;
this.SubItem = SubItem;
this.flags = flags;
inflter = (LayoutInflater.from(applicationContext));
}
#Override
public int getCount() {
return Item.length;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = inflter.inflate(R.layout.activity_items, null);
//TextView Prueba = (TextView)view.findViewById(R.id.KMlabel);
TextView item = (TextView) view.findViewById(R.id.item);
TextView subitem = (TextView) view.findViewById(R.id.subitem);
ImageView image = (ImageView) view.findViewById(R.id.image);
item.setText(Item[i]);
subitem.setText(SubItem[i]);
image.setImageResource(flags[i]);
return view;
}
viewdialog.java
public class ViewDialog {
public void showDialog(Activity activity, String msg){
final Dialog dialog = new Dialog(activity);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(false);
dialog.setContentView(R.layout.custom_dialog);
//I'm declaring it like this
final TextView KMLabel = (TextView)activity.findViewById(R.id.KMlabel);
Button dialogButton = (Button) dialog.findViewById(R.id.btn_dialog);
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
Button KmPerHr = (Button)dialog.findViewById(R.id.KmPerH);
KmPerHr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//and calling it this way:
KMLabel.setText("MLL/H");
}
});
dialog.show();
}
}
LOGCAT:
FATAL EXCEPTION: main
Process: com.example.dell.getspeed, PID: 3925
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.example.dell.getspeed.ViewDialog$2.onClick(ViewDialog.java:38)
at android.view.View.performClick(View.java:5721)
at android.widget.TextView.performClick(TextView.java:10936)
at android.view.View$PerformClick.run(View.java:22620)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7406)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
You have to move your code
Button KmPerHr = (Button)dialog.findViewById(R.id.KmPerH);
KmPerHr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//and calling it this way:
KMLabel.setText("MLL/H");
}
});
final TextView KMLabel = (TextView)dialog.findViewById(R.id.KMlabel);
Button dialogButton = (Button) dialog.findViewById(R.id.btn_dialog);
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
below the dialog.show() code because code findViewById only work after you pop up dialog.
Create a Global class which extends to application class, then create a texview in Global
Textview t = null;
Then create two static methods to set and get this textview
Public static void setT(TextView p){
t = p;
}
And get it from
Public static TextView getT(){
return t;
}
Set TextView in your activity ,then access this textview from wherever you want until your activity is alive.
Try the code below:
MainActivity class:-------
public class MainActivity extends AppCompatActivity {
private TextView KMlabel;
private Button b;
private ViewDialog vd;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo2);
vd = new ViewDialog();
KMlabel = (TextView) findViewById(R.id.KMlabel);
b = (Button) findViewById(R.id.b);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
vd.showDialog(MainActivity.this , KMlabel , "Your Message" , "Your Text");
}
});
}
}
ViewDialog class:------
public class ViewDialog {
public void showDialog(Context context, final TextView v , String msg , final String text) {
createYesNoInfoDialog(context, msg, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
}, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
v.setText(text);
}
}).show();
}
private AlertDialog createYesNoInfoDialog(Context finalContext, String message,
DialogInterface.OnClickListener onNoListener, DialogInterface.OnClickListener onYesListener) {
AlertDialog a = new AlertDialog.Builder(finalContext).setTitle(
message)
.setNegativeButton("No", onNoListener)
.setPositiveButton("Yes", onYesListener).create();
return a;
}
}
demo2.xml:-----
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="xcxc"
android:id="#+id/KMlabel"/>
<Button
android:layout_width="match_parent"
android:text="Create Dialog"
android:layout_height="wrap_content"
android:id="#+id/b"/>
</LinearLayout>
R.id.KMlabel is on activity_main.xml so you have to initialize the TextView from MainActivity reference.
final TextView KMLabel = (TextView)activity.findViewById(R.id.KMlabel);
Edit:
You can use callback pattern for this:
ViewDialog:
public class ViewDialog {
// interface for callback
public interface OnSelectListener {
public void onOkSelect();
}
OnSelectListener mOnSelectListener;
public void showDialog(Activity activity, String msg, OnSelectListener mListener){
mOnSelectListener = mListener;
final Dialog dialog = new Dialog(activity);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(false);
dialog.setContentView(R.layout.custom_dialog);
//I'm declaring it like this
final TextView KMLabel = (TextView)activity.findViewById(R.id.KMlabel);
Button dialogButton = (Button) dialog.findViewById(R.id.btn_dialog);
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
Button KmPerHr = (Button)dialog.findViewById(R.id.KmPerH);
KmPerHr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//pass to the implementation if not null
if( mOnSelectListener != null){
mOnSelectListener.onOkSelect();
}
}
});
dialog.show();
}
}
In MainActivity:
// initialize interface
ViewDialog.OnSelectListener mOnSelectListener = new ViewDialog.OnSelectListener(){
public void onOkSelect(){
KMLabel.setText("MLL/H");
}
};
ViewDialog viewDialog = new ViewDialog();
viewDialog.showDialog(this, "Message", mOnSelectListener);
This happens since you are trying to call the TextView within the custom alert dialog. TextView only belongs to the MainActivity. You can call or change that only within the MainActivity class. So please try this below.
MainActivity.class
public class MainActivity extends AppCompatActivity {
private TextView KMlabel;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
KMlabel = (TextView) findViewById(R.id.KMlabel);
}
public void setTextKM(String string){
KMlabel.setText(string);
}
}
ViewDialog class
public class ViewDialog {
public void showDialog(Activity activity, String msg){
final Dialog dialog = new Dialog(activity);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(false);
dialog.setContentView(R.layout.custom_dialog);
Button dialogButton = (Button) dialog.findViewById(R.id.btn_dialog);
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
Button KmPerHr = (Button)dialog.findViewById(R.id.KmPerH);
KmPerHr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MainActivity mainActivity = new MainActivity();
mainActivity.setTextKM("MLL/H");
}
});
dialog.show();
}
}

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