There is a program where I can change a variable using a singleton. Created 2 activites, where users can change this variable. How to write the variable that is being changed to the Firebase database. I tried to use the addValueEventListener (new ValueEventListener () method.
Where do I use the firebase methods? In the main class or in singleton? And how to write a variable?
main activity
public class MainActivity extends AppCompatActivity {
private BubbleWrap bubbleWrap;
private TextView txtintent;
final int REQUEST_CODE_661_1 = 1;
private int bbbbb;
private TextView txt;
private String bubul;
FirebaseDatabase database=FirebaseDatabase.getInstance();
final DatabaseReference AllFacebase =database.getReference("всего").child("йй");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt=findViewById(R.id.textView);
bubbleWrap=BubbleWrap.getInstance();
setupAddMoreButton();
setupPopActivityButton();
setupCocActivityButton();
txtintent=(TextView)findViewById(R.id.txtintent);
AllFacebase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
bubul=String.valueOf(dataSnapshot.getValue());
txtintent.setText(bubul);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
protected void onResume() {
super.onResume();
updateUI();
}
private void setupAddMoreButton(){
Button btn=findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bubbleWrap.addMoreBubbles();
updateUI();
}
});
}
private void setupPopActivityButton(){
Button btn=findViewById(R.id.button2);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
private void setupCocActivityButton(){
Button btn=findViewById(R.id.buttoncoc);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
private void updateUI(){
txtintent.setText(String.format(Locale.getDefault(),"%d",
bubbleWrap.getNumBubbles()));
}
}
second activity
activity, where I change the variable, I want to write to Firebase
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pop);
bubbleWrap=BubbleWrap.getInstance();
final TextView txt=findViewById(R.id.textView2);
setupPopButton();
updateUI();
Intent intent=new Intent();
intent.putExtra("bubles", bubbleWrap.getNumBubbles());
}
private void setupPopButton(){
Button btn=findViewById(R.id.cocbtb);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bubbleWrap.popBubble();
updateUI();
}
});
}
private void updateUI(){
TextView txt=findViewById(R.id.textView2);
txt.setText(String.format(Locale.getDefault(),
"Bubbles left: %d",
bubbleWrap.getNumBubbles()));
}
}
Singleton
public class BubbleWrap {
private static final int ADD_MORE_BUBBLES = 10;
private int numBubbles;
private static BubbleWrap instance;
private BubbleWrap(){
}
public static BubbleWrap getInstance(){
if(instance==null){
instance=new BubbleWrap();
}
return instance;
}
public int getNumBubbles() {
return numBubbles;
}
public void addMoreBubbles(){
numBubbles+=ADD_MORE_BUBBLES;
}
public void popBubble() {
numBubbles--;
}
public void saveintent(){
}
}
Related
Is there any way to stop the progress bar from other class which is started in mainActivity
Kindly find the code
I am starting the progress bar in the main activity and then calling the method of other java class
where I am inserting data in firebase
I just want that after firebase insertion is successful progress bar should stop
but didn't find any way to do that
public class ProductDetails extends AppCompatActivity {
ProgressBar progressbar;
Button btn;
FirebaseDatabase firebaseDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_details);
progressbar = findViewById(R.id.btnprogressbar);
btn = findViewById(R.id.submit_btn);
firebaseDatabase = FirebaseDatabase.getInstance();
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressbar.setVisibility(View.VISIBLE);
submitForm();
}
});
}
private void submitForm() {
FormDetailsServices formDetailsServices = new FormDetailsServices(ProductDetails.this);
FormDTO formDTO=generateForDTO();
formDetailsServices.submitForm(formDTO,firebaseDatabase);
}
}
My FormDetailsServices:
public class FormDetailsServices {
Context context;
final String TAG = "FormDetailsServices";
public FormDetailsServices(Context context) {
this.context = context;
}
public Context getContext() {
return context;
}
public void setContext(Context context) {
this.context = context;
}
public void submitForm(FormDTO formDTO,FirebaseDatabase firebaseDatabase) {
firebaseDatabase
.getReference()
.child("test")
.setValue(formDTO)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG,"form submitted Successfully");
//here i want to stop progressbar
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG,"form submittion Failed exception msg= " + e.getMessage());
}
});
}
}
Everything is working fine its getting inserted to Firebase but progressbar is still visible
You can create an interface in FormDetailsServices class and implement it to your main class, and then you can hide the progress bar by calling its methods in main class as below -
public class ProductDetails extends AppCompatActivity implements FormDetailsServices.OnFormSubmissionListener{
ProgressBar progressbar;
Button btn;
FirebaseDatabase firebaseDatabase;
OnFormSubmissionListener listener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_details);
progressbar = findViewById(R.id.btnprogressbar);
btn = findViewById(R.id.submit_btn);
firebaseDatabase = FirebaseDatabase.getInstance();
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressbar.setVisibility(View.VISIBLE);
submitForm();
}
});
}
private void submitForm() {
FormDetailsServices formDetailsServices = new
FormDetailsServices(ProductDetails.this);
formDetailsServices.setOnFormSubmissionListener(this);
FormDTO formDTO=generateForDTO();
formDetailsServices.submitForm(formDTO,firebaseDatabase);
}
#Override
public void onSubmissionSuccess() {
progressbar.setVisibility(View.GONE);
}
#Override
public void onSubmissionFailure() {
progressbar.setVisibility(View.GONE);
}
}
and for FormDetailsServices
public class FormDetailsServices {
Context context;
final String TAG = "FormDetailsServices";
OnFormSubmissionListener listener;
public FormDetailsServices(Context context) {
this.context = context;
}
public Context getContext() {
return context;
}
public void setContext(Context context) {
this.context = context;
}
void setOnFormSubmissionListener(OnFormSubmissionListener listener){
this.listener = listener;
}
public void submitForm(FormDTO formDTO,FirebaseDatabase firebaseDatabase) {
firebaseDatabase
.getReference()
.child("test")
.setValue(formDTO)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG,"form submitted Successfully");
//here i want to stop progressbar
listener.onSubmissionSuccess();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
listener.onSubmissionFailure();
Log.d(TAG,"form submittion Failed exception msg= " + e.getMessage());
}
});
}
interface OnFormSubmissionListener {
void onSubmissionSuccess();
void onSubmissionFailure();
}
}
if the page is loaded, the button is active, if not, how can I do passive control?
What I want to do is, if the Viewpager Page is loaded, the button is active, if not, the Button is Passive. But I couldn't do any kind.
Is there anyone who can help?
If viewpager2 is installed Button enabled, if viewpager2 is not installed button false;
List<Movie> movieList = new ArrayList<>();
private ImageButton btn_down, btn_fav;
private Button btn_setter;
private DatabaseReference movies;
private IFirebaseLoadDone iFirebaseLoadDone;
public CartoonFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_cartoon, container, false);
movies = FirebaseDatabase.getInstance().getReference("Sports");
movies.keepSynced(true);
iFirebaseLoadDone = this;
loadMovie();
viewPager2 = view.findViewById(R.id.viewPager2_);
btn_down = view.findViewById(R.id.btn_down);
btn_setter = view.findViewById(R.id.btn_setter);
btn_fav = view.findViewById(R.id.btn_fav);
btn_down.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SaveToGallery();
}
});
btn_setter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
btn_fav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return view;
}
private void loadMovie() {
movies.addValueEventListener(this);
}
#Override
public void onFirebaseLoadSuccess(List<Movie> movieList) {
viewPagerAdapter = new ViewPagerAdapter(getContext(), movieList, viewPager2);
viewPager2.setAdapter(viewPagerAdapter);
}
#Override
public void onFirebasLoadFailed(String message) {
}
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot moviesSnapShot : dataSnapshot.getChildren())
movieList.add(moviesSnapShot.getValue(Movie.class));
Collections.reverse(movieList);
iFirebaseLoadDone.onFirebaseLoadSuccess(movieList);
viewPagerAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
iFirebaseLoadDone.onFirebasLoadFailed(databaseError.getMessage());
}
#Override
public void onDestroy() {
movies.removeEventListener(this);
super.onDestroy();
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onStop() {
movies.removeEventListener(this);
super.onStop();
}
}
Replace your methods with mine.
private void loadMovie() {
movies.addValueEventListener(this);
btn_down.setEnabled(false);
btn_fav.setEnabled(false);
btn_setter.setEnabled(false);
}
Firebase methods
#Override
public void onFirebaseLoadSuccess(List<Movie> movieList) {
viewPagerAdapter = new ViewPagerAdapter(getContext(), movieList, viewPager2);
viewPager2.setAdapter(viewPagerAdapter);
if(movieList!=null && !movieList.isEmpty()){
btn_down.setEnabled(true);
btn_fav.setEnabled(true);
btn_setter.setEnabled(true);
}
}
#Override
public void onFirebasLoadFailed(String message) {
btn_down.setEnabled(false);
btn_fav.setEnabled(false);
btn_setter.setEnabled(false);
}
There was an error loading
private void loadMovie() {
movies.addValueEventListener(this);
btn_down.setEnabled(false);
btn_fav.setEnabled(false);
btn_setter.setEnabled(false);
}
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageButton.setEnabled(boolean)' on a null object reference
at com.example.duvarlar.Fragment.CartoonFragment.loadMovie(CartoonFragment.java:386)
at com.example.duvarlar.Fragment.CartoonFragment.onCreateView(CartoonFragment.java:90)
My settext do not update after I have updated it's value from database. But if I logout and login into my app settext is refreshed.I get the value of settext by SharedPreferences.
public class MySettingsActivity extends AppCompatActivity {
private TextView settingsDisplayName;
private TextView settingsDisplayStatus;
private User user = SharedPrefManager.getInstance(this).getUser();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_settings);
settingsDisplayName = (TextView) findViewById (R.id.settings_username);
settingsDisplayStatus = (TextView) findViewById(R.id.settings_status);
settingsChangeUsername.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String old_name = settingsDisplayName.getText().toString();
Intent usernameIntent = new Intent(MySettingsActivity.this, UsernameActivity.class);
usernameIntent.putExtra("user_name",old_name );
startActivity(usernameIntent);
}
});
}
#Override
protected void onStart() {
MySettingsActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
settingsDisplayName.setText(user.getName());
settingsDisplayStatus.setText(user.getEmail());
}
});
super.onStart();
}
}
public class MainActivity extends AppCompatActivity {
//points to the root node of the database
DatabaseReference mRootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference mConditionRef = mRootRef.child("condition");
TextView content;
Button sunny, foggy;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
content = (TextView) findViewById(R.id.condition);
sunny = (Button) findViewById(R.id.sunny);
foggy = (Button) findViewById(R.id.foggy);
}
#Override
protected void onStart() {
super.onStart();
mConditionRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String text = dataSnapshot.getValue(String.class);
content.setText(text);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
sunny.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mConditionRef.setValue("Sunny");
mRootRef.child("condition").push().setValue("Abhijeet Jain2");
}
});
foggy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mConditionRef.setValue("Foggy");
}
});
}
}
The string gets added in the realtime database with a automatic made id but the app crashes as soon as I press the button "sunny".
What could be the reason and the solution?
I want to show Firebase data filtered by userID. But the app crashes and after debugging it shows a NullPointerException on the Firebase adapter. What to do? I am implementing it in fragment. I am not pasting the imported libraries.
Here is my code:
public class MyPosts extends Fragment{
private RecyclerView postList;
private DatabaseReference mDatabase;
private DatabaseReference mDatabaseAppriciate;
private DatabaseReference mDatabaseDisgrace;
private LinearLayoutManager layoutManager;
private FirebaseAuth mAuth= FirebaseAuth.getInstance();
private DatabaseReference mDatabaseCurrentUser;
public Query mQueryCurrentUser=null;
//private static final String TAG = "MyActivity";
private boolean mProcessAppriciate=false;
private boolean mProcessDisgrace=false;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
View rootView = inflater.inflate(R.layout.allposts, container, false);
mDatabase= FirebaseDatabase.getInstance().getReference().child("Posts");
mDatabaseAppriciate=FirebaseDatabase.getInstance().getReference().child("Appriciate");
mDatabaseDisgrace=FirebaseDatabase.getInstance().getReference().child("Disgrace");
mDatabase.keepSynced(true);
mDatabaseAppriciate.keepSynced(true);
mDatabaseDisgrace.keepSynced(true);
//EXPERIMENT WITH LISTVIEW STARTS
postList=(RecyclerView) rootView.findViewById(R.id.postList);
postList.setHasFixedSize(true);
layoutManager=new LinearLayoutManager(getActivity());
layoutManager.setReverseLayout(true);
postList.setHasFixedSize(true);
postList.setLayoutManager(layoutManager);
postList.getRecycledViewPool().clear();
//EXPERIMENT WITH LISTVIEW ENDS
return rootView;
}
#Override
public void onStart() {
super.onStart();
//EXP CODE STARTS
FirebaseAuth.getInstance().addAuthStateListener(new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
mDatabaseCurrentUser=FirebaseDatabase.getInstance().getReference().child("Posts");
String currentUserId=user.getUid();
mQueryCurrentUser=mDatabaseCurrentUser.orderByChild("uid").equalTo(currentUserId);
}else{
}
}
});
//EXP CODE ENDS
FirebaseRecyclerAdapter<Posts,PostViewHolder> firebaseRecyclerAdapter= new FirebaseRecyclerAdapter<Posts,PostViewHolder>(
Posts.class,
R.layout.single_post,
PostViewHolder.class,
mQueryCurrentUser
) {
#Override
protected void populateViewHolder(final PostViewHolder viewHolder, final Posts model, final int position) {
final String post_key=getRef(position).getKey();
viewHolder.setTitle(model.getTitle());
viewHolder.setDescription(model.getDescription());
viewHolder.setProfileName(model.getProfilename());
viewHolder.setImage(getContext(),model.getImage());
viewHolder.getLayoutPosition();
viewHolder.setAppriciateButton(post_key);
viewHolder.setDisgraceButton(post_key);
//Share click code below
viewHolder.Share.setOnClickListener(new View.OnClickListener() {
CallbackManager callbackManager;
ShareDialog shareDialog;
#Override
public void onClick(View v) {
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
shareDialog = new ShareDialog(MyPosts.this);
if (ShareDialog.canShow(ShareLinkContent.class)) {
ShareLinkContent content = new ShareLinkContent.Builder()
.setContentTitle(model.getTitle())
.setContentDescription(model.getDescription())
.setImageUrl(Uri.parse(model.getImage()))
.setContentUrl(Uri.parse("https://developers.facebook.com"))
.build();
shareDialog.show(content);
shareDialog.registerCallback(callbackManager, new FacebookCallback<Sharer.Result>() {
#Override
public void onSuccess(Sharer.Result result) {
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
});
}
}
});
//Share click code ends above
//Appriciate button on click event below
viewHolder.Appriciate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mProcessAppriciate=true;
mDatabaseAppriciate.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (mProcessAppriciate) {
if (dataSnapshot.child(post_key).hasChild(mAuth.getCurrentUser().getUid())) {
mDatabaseAppriciate.child(post_key).child(mAuth.getCurrentUser().getUid()).removeValue();
mProcessAppriciate = false;
}else {
mDatabaseAppriciate.child(post_key).child(mAuth.getCurrentUser().getUid()).setValue(mAuth.getCurrentUser().getDisplayName());
mProcessAppriciate = false;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
//Appriciate button click event CODE ENDS
//Disgrace Button Click Event Code Starts
viewHolder.Disgrace.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mProcessDisgrace=true;
mDatabaseDisgrace.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (mProcessDisgrace) {
if (dataSnapshot.child(post_key).hasChild(mAuth.getCurrentUser().getUid())) {
mDatabaseDisgrace.child(post_key).child(mAuth.getCurrentUser().getUid()).removeValue();
mProcessDisgrace = false;
} else {
mDatabaseDisgrace.child(post_key).child(mAuth.getCurrentUser().getUid()).setValue(mAuth.getCurrentUser().getDisplayName());
mProcessDisgrace = false;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
//Disgrace Button Click code Ends
}
};
postList.setAdapter(firebaseRecyclerAdapter);
//test code
firebaseRecyclerAdapter.notifyDataSetChanged();
}
public static class PostViewHolder extends RecyclerView.ViewHolder{
View mView;
Button Appriciate;
Button Disgrace;
Button Share;
DatabaseReference mDatabaseAppriciate;
DatabaseReference mDatabaseDisgrace;
FirebaseAuth mAuth;
public PostViewHolder(View itemView) {
super(itemView);
mView=itemView;
Appriciate=(Button) mView.findViewById(R.id.appriciate);
Disgrace=(Button) mView.findViewById(R.id.disgraceful);
Share=(Button) mView.findViewById(R.id.share);
mDatabaseAppriciate=FirebaseDatabase.getInstance().getReference().child("Appriciate");
mDatabaseDisgrace=FirebaseDatabase.getInstance().getReference().child("Disgrace");
mAuth=FirebaseAuth.getInstance();
mDatabaseAppriciate.keepSynced(true);
mDatabaseDisgrace.keepSynced(true);
}
public void setAppriciateButton(final String post_key){
mDatabaseAppriciate.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.child(post_key).hasChild(mAuth.getCurrentUser().getUid())){
Appriciate.setBackgroundColor(Color.GRAY);
Appriciate.setText("Appriciated");
}else{
Appriciate.setBackgroundColor(Color.GREEN);
Appriciate.setText("APPRICIATE");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
//SET DISGRACE BUTTON CODE BELOW
public void setDisgraceButton(final String post_key){
mDatabaseDisgrace.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.child(post_key).hasChild(mAuth.getCurrentUser().getUid())){
Disgrace.setBackgroundColor(Color.GRAY);
Disgrace.setText("Disgraced");
}else{
Disgrace.setBackgroundColor(Color.RED);
Disgrace.setText("DISGRACE");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
//SET DISGRACE BUTTON CODE ENDS
//Setting the title to the AllActivity
public void setTitle(String title){
TextView postTitle=(TextView) mView.findViewById(R.id.allPostTitle);
postTitle.setText(title);
}
public void setDescription(String description){
TextView postDescription=(TextView) mView.findViewById(R.id.allPostDescription);
postDescription.setText(description);
}
//PROFILE NAME EXPERIMENT
public void setProfileName(String profilename){
TextView postName=(TextView) mView.findViewById(R.id.profileName);
postName.setText(profilename);
}
public void setImage(final Context context, final String image) {
final ImageView postImage=(ImageView) mView.findViewById(R.id.allPostImage);
with(context).load(image).networkPolicy(NetworkPolicy.OFFLINE).into(postImage, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
Picasso.with(context).load(image).resize(500,700).into(postImage);
}
});
}
//THREADING EXPERIMENT CODE
}
}