I'm trying to save user's data in my database but i sometimes get null value from:
currentUser = dataSnapshot.getValue(User.class);
the key is correctly to the user id but the value is null
Here is my code:
package com.example.eltobgy.yala;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import com.firebase.ui.auth.AuthUI;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static final String ANONYMOUS = "Anonymous";
// Choose an arbitrary request code value
private static final int RC_SIGN_IN = 1;
public static DatabaseReference mDatabaseReference;
public static FirebaseDatabase mDatabase;
public static User currentUser;
// Firebase
private FirebaseAuth mFirebaseAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
private ChildEventListener mChildEventListener;
private String mUsername;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Signing you in ...");
progressDialog.show();
mUsername = ANONYMOUS;
mFirebaseAuth = FirebaseAuth.getInstance();
mDatabase = FirebaseDatabase.getInstance();
currentUser = null;
mDatabaseReference = mDatabase.getReference().child("users");
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
if (firebaseUser != null) {
// User is signed in
onSignedInInitialize(firebaseUser.getDisplayName());
DatabaseReference userDatabaseRefrence = mDatabaseReference.child(firebaseUser.getUid());
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
currentUser = dataSnapshot.getValue(User.class);
progressDialog.dismiss();
if (currentUser.isBasicInfo()) {
if (currentUser.getCurrentType().equals("")) {
Intent intent = new Intent(MainActivity.this, UserTypeActivity.class);
startActivity(intent);
} else if (currentUser.getCurrentType().equals("t")) {
if (!currentUser.isDeliveryModeActivation()) {
Intent intent = new Intent(MainActivity.this, DeliveryManExtraInfoActivity.class);
startActivity(intent);
} else {
Intent intent = new Intent(MainActivity.this, HomeActivity.class);
startActivity(intent);
}
} else {
Intent intent = new Intent(MainActivity.this, HomeActivity.class);
startActivity(intent);
}
} else {
Intent intent = new Intent(MainActivity.this, BasicInfoActivity.class);
startActivity(intent);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(MainActivity.this, "cancelled", Toast.LENGTH_SHORT).show();
}
};
userDatabaseRefrence.addValueEventListener(valueEventListener);
} else {
// User is signed out
onSignedOutCleanup();
List<AuthUI.IdpConfig> providers = Arrays.asList(
new AuthUI.IdpConfig.Builder(AuthUI.EMAIL_PROVIDER).build(),
new AuthUI.IdpConfig.Builder(AuthUI.GOOGLE_PROVIDER).build());
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setIsSmartLockEnabled(false)
.setAvailableProviders(providers)
.setTheme(R.style.LoginTheme)
.build(),
RC_SIGN_IN);
}
}
};
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
if (resultCode == RESULT_OK) {
// Sign-in succeeded, set up the UI
mDatabaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!dataSnapshot.exists()) {
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
User user = new User(firebaseUser.getUid(), firebaseUser.getDisplayName(), firebaseUser.getEmail());
mDatabaseReference.child(user.getId()).setValue(user);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else if (resultCode == RESULT_CANCELED) {
// Sign in was canceled by the user, finish the activity
Toast.makeText(this, "Sign in canceled", Toast.LENGTH_SHORT).show();
finish();
}
}
}
private void onSignedInInitialize(String username) {
mUsername = username;
}
private void onSignedOutCleanup() {
mUsername = ANONYMOUS;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.sign_out_menu:
AuthUI.getInstance().signOut(this).addOnCompleteListener(new OnCompleteListener<Void>() {
public void onComplete(#NonNull Task<Void> task) {
// user is now signed out
startActivity(new Intent(MainActivity.this, MainActivity.class));
finish();
}
});
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onPause() {
super.onPause();
if (mAuthStateListener != null) {
mFirebaseAuth.removeAuthStateListener(mAuthStateListener);
}
//mMessageAdapter.clear();
//detachDatabaseReadListener();
}
#Override
protected void onResume() {
super.onResume();
mFirebaseAuth.addAuthStateListener(mAuthStateListener);
}
}
And my User.java class
package com.example.eltobgy.yala;
import java.io.Serializable;
public class User implements Serializable {
private String id;
private String name;
private String phone;
private String email;
private String photoUrl;
private String currentType; //c for customer, d for delivery man
private boolean deliveryModeActivation;
private int rating;
private String gender; //u:unkown, f:female, m:male
private Birthday birthday;
private boolean basicInfo;
public User(String id, String name, String email) {
this.id = id;
this.name = name;
this.phone = "";
this.email = email;
this.currentType = "";
this.deliveryModeActivation = false;
this.rating = 0;
photoUrl = "";
gender = "u";
birthday = new Birthday(0, 0, 0);
basicInfo = false;
}
public User() {
}
public boolean isBasicInfo() {
return basicInfo;
}
public void setBasicInfo(boolean basicInfo) {
this.basicInfo = basicInfo;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Birthday getBirthday() {
return birthday;
}
public void setBirthday(Birthday birthday) {
this.birthday = birthday;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCurrentType() {
return currentType;
}
public void setCurrentType(String currentType) {
this.currentType = currentType;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhotoUrl() {
return photoUrl;
}
public void setPhotoUrl(String photoUrl) {
this.photoUrl = photoUrl;
}
public boolean isDeliveryModeActivation() {
return deliveryModeActivation;
}
public void setDeliveryModeActivation(boolean deliveryModeActivation) {
this.deliveryModeActivation = deliveryModeActivation;
}
public int getRating() {
return rating;
}
public void setRating(int rating) {
this.rating = rating;
}
}
And my database
Related
Please I don't understand the error.java.lang.IllegalStateException: Expected a string but was BEGIN_ARRAY at line 1 column 28 path $.message retrofit android studio Please I need your help
package com.sensei.linkrestaurant;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.material.navigation.NavigationView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.firebase.auth.FirebaseAuth;
import com.sensei.linkrestaurant.Adapter.MyRestaurantAdapter;
import com.sensei.linkrestaurant.Adapter.RestaurantSliderAdapter;
import com.sensei.linkrestaurant.Common.Common;
import com.sensei.linkrestaurant.Model.EventBus.RestaurantLoadEvent;
import com.sensei.linkrestaurant.Model.Restaurant;
import com.sensei.linkrestaurant.Retrofit.ILinkRestaurantAPI;
import com.sensei.linkrestaurant.Retrofit.RetrofitClient;
import com.sensei.linkrestaurant.Service.PicassoImageLoadingService;
import com.sensei.linkrestaurant.databinding.ActivityHomeBinding;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import butterknife.BindView;
import butterknife.ButterKnife;
import dmax.dialog.SpotsDialog;
import io.paperdb.Paper;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers;
import ss.com.bannerslider.Slider;
public class HomeActivity extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener{
private static final String TAG = "HomeActivity";
private AppBarConfiguration mAppBarConfiguration;
private ActivityHomeBinding binding;
TextView txt_user_name, txt_user_phone;
#BindView(R.id.banner_slider)
Slider banner_slider;
#BindView(R.id.recycler_restaurant)
RecyclerView recyclerView;
private ILinkRestaurantAPI iLinkRestaurantAPI;
private final CompositeDisposable compositeDisposable = new CompositeDisposable();
private AlertDialog dialog;
#Override
protected void onDestroy() {
compositeDisposable.clear();
super.onDestroy();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityHomeBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
setSupportActionBar(binding.appBarHome.toolbar);
DrawerLayout drawer = binding.drawerLayout;
NavigationView navigationView = binding.navView;
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow)
.setOpenableLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this,
R.id.nav_host_fragment_content_link_main2);
NavigationUI.setupActionBarWithNavController(this, navController,
mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
View headerView = navigationView.getHeaderView(0);
txt_user_name = headerView.findViewById(R.id.txt_user_name);
txt_user_phone = headerView.findViewById(R.id.txt_user_phone);
txt_user_name.setText(Common.currentUser.getName());
txt_user_phone.setText(Common.currentUser.getUserPhone());
navigationView.setNavigationItemSelectedListener(this);
init();
initView();
loadRestaurant();
}
private void init() {
dialog = new SpotsDialog.Builder().setContext(this).setCancelable(false).build();
iLinkRestaurantAPI = RetrofitClient
.getInstance(Common.API_RESTAURANT_ENDPOINT).create(ILinkRestaurantAPI.class);
Slider.init(new PicassoImageLoadingService());
}
private void initView() {
ButterKnife.bind(this);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.addItemDecoration(new DividerItemDecoration(this,
layoutManager.getOrientation()));
}
private void loadRestaurant() {
dialog.show();
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", Common.buildJWT(Common.API_KEY));
compositeDisposable.add(
iLinkRestaurantAPI.getRestaurant(headers)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(restaurantModel -> {
//Event bus to send local even to set adapter and slider
EventBus.getDefault().post(new RestaurantLoadEvent(true,
restaurantModel.getResult()));
dialog.dismiss();
},
throwable ->{
dialog.dismiss();
EventBus.getDefault().post(new RestaurantLoadEvent(false,
throwable.getMessage()));
Toast.makeText(this, "[GET RESTAURANT]"+throwable.getMessage(),
Toast.LENGTH_SHORT).show();
})
);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this,
R.id.nav_host_fragment_content_link_main2);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_log_out){
signOut();
} else if (id == R.id.nav_nearby){
startActivity(new Intent(HomeActivity.this, NearbyRestaurantActivity.class));
} else if(id == R.id.order_history){
startActivity(new Intent(HomeActivity.this, ViewOrderActivity.class));
} else if(id == R.id.update_information){
startActivity(new Intent(HomeActivity.this, UpdateInfoActivity.class));
}else if (id == R.id.nav_fav){
startActivity(new Intent(HomeActivity.this, FavoriteActivity.class));
}
return true;
}
private void signOut() {
AlertDialog confirmExit = new AlertDialog.Builder(this)
.setTitle("Sign Out")
.setMessage("Do you really want to Sign Out")
.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Common.currentUser = null;
Common.currentRestaurant = null;
FirebaseAuth.getInstance().signOut();
Intent intent = new Intent(HomeActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
}).create();
confirmExit.show();
}
//Register Event Bus
#Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
#Override
public void onStop() {
EventBus.getDefault().unregister(this);
super.onStop();
}
//Listen Event Bus
#Subscribe(threadMode = ThreadMode.MAIN)
public void processRestaurantLoadEvent(RestaurantLoadEvent event) {
if (event.isSuccess()){
displayBanner(event.getRestaurantList());
displayRestaurant(event.getRestaurantList());
}else{
Toast.makeText(this, "[RESTAURANT LOAD]" + event.getMessage(),
Toast.LENGTH_LONG).show();
}
dialog.dismiss();
}
private void displayRestaurant(List<Restaurant> restaurantList) {
MyRestaurantAdapter adapter = new MyRestaurantAdapter(this, restaurantList);
recyclerView.setAdapter(adapter);
}
private void displayBanner(List<Restaurant> restaurantList) {
banner_slider.setAdapter(new RestaurantSliderAdapter(restaurantList));
}
}
This is the Handles the loadEvent
package com.sensei.linkrestaurant.Model.EventBus;
import com.sensei.linkrestaurant.Model.Restaurant;
import java.util.List;
public class RestaurantLoadEvent {
private boolean success;
private String message;
private List<Restaurant> restaurantList;
public RestaurantLoadEvent() {
}
public RestaurantLoadEvent(boolean success, String message) {
this.success = success;
this.message = message;
}
public RestaurantLoadEvent(boolean success, List<Restaurant> restaurantList) {
this.success = success;
this.restaurantList = restaurantList;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<Restaurant> getRestaurantList() {
return restaurantList;
}
public void setRestaurantList(List<Restaurant> restaurantList) {
this.restaurantList = restaurantList;
}
}
This is the Restaurant Class
package com.sensei.linkrestaurant.Model;
public class Restaurant {
//Remember all variable names has to be exactly as Json property return from API
//That will help Gson to parse it correctly
private int id;
private String name;
private String address;
private String phone;
private Float lat;
private Float lng;
private int userOwner;
private String image;
private String paymentUrl;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Float getLat() {
return lat;
}
public void setLat(Float lat) {
this.lat = lat;
}
public Float getLng() {
return lng;
}
public void setLng(Float lng) {
this.lng = lng;
}
public int getUserOwner() {
return userOwner;
}
public void setUserOwner(int userOwner) {
this.userOwner = userOwner;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getPaymentUrl() {
return paymentUrl;
}
public void setPaymentUrl(String paymentUrl) {
this.paymentUrl = paymentUrl;
}
}
This is the Retrofit client for the ILinkRestaurantAPI
#GET("restaurant")
Observable<RestaurantModel> getRestaurant(#HeaderMap Map<String, String> headers);
This is the Restaurant model
package com.sensei.linkrestaurant.Model;
import java.util.List;
public class RestaurantModel {
private boolean success;
private String message;
private List<Restaurant> result;
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<Restaurant> getResult() {
return result;
}
public void setResult(List<Restaurant> result) {
this.result = result;
}
}
I think you must change Observable to Observable<RestaurantModel[]>
or in anather place you have strign but API give array, check API response and compare with your model (use for example tool Postman)
try and give response if help
[EDIT]
try private String message[];
[EDIT2]
in API message it's not String it's Array of object
Previously, i login a user and display its personal information in Textviews and it works fine for the first time, but when i sign-out and entered another user, the information of the previous user is still shown in the textview which supposedly his own personal data. I tried to login with a third user and still display the information of the first user. Here are my codes.. Your help is highly appreciated.
Userinformation.java
public class Userinformation {
private String establishmentname;
private String address;
private String contact;
private String availability;
private String price;
private String type;
private String condition;
private String ownername;
public Userinformation(){
}
public Userinformation (String establishmentname ,String address,String contact, String availability, String price, String type, String condition, String ownername){
this.establishmentname=establishmentname;
this.address=address;
this.contact=contact;
this.availability=availability;
this.price=price;
this.type=type;
this.condition=condition;
this.ownername=ownername;
}
public String getEstablishmentname() {
return establishmentname;
}
public void setEstablishmentname(String establishmentname) {
this.establishmentname = establishmentname;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
public String getAvailability() {
return availability;
}
public void setAvailability(String availability) {
this.availability = availability;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getCondition() {
return condition;
}
public void setCondition(String condition) {
this.condition = condition;
}
public String getOwnername() {
return ownername;
}
public void setOwnername(String ownername) {
this.ownername = ownername;
}
}
Profile.java
package *****************;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class Profile extends AppCompatActivity implements View.OnClickListener {
ImageView userprofile;
TextView establishmentdisplay;
TextView addressdisplay;
TextView contactdisplay;
TextView availabilitydisplay;
TextView pricedisplay;
TextView typedisplay;
TextView conditiondisplay;
TextView ownernamedisplay;
Button btnsave;
private FirebaseAuth mAuth;
private FirebaseDatabase mFirebaseDatabase;
private FirebaseAuth.AuthStateListener mAuthListener;
DatabaseReference myRef;
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
userprofile=(ImageView) findViewById(R.id.userprofile);
btnsave = (Button) findViewById(R.id.savechangesbtn);
establishmentdisplay = (TextView) findViewById(R.id.establishmentdisplay);
addressdisplay = (TextView) findViewById(R.id.addressdisplay);
contactdisplay = (TextView) findViewById(R.id.contactdisplay);
availabilitydisplay = (TextView) findViewById(R.id.availabilitydisplay);
pricedisplay = (TextView) findViewById(R.id.pricedisplay);
typedisplay = (TextView) findViewById(R.id.typedisplay);
conditiondisplay = (TextView) findViewById(R.id.conditiondisplay);
ownernamedisplay = (TextView) findViewById(R.id.ownernamedisplay);
btnsave.setOnClickListener(this);
mAuth = FirebaseAuth.getInstance();
final FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference user = database.getReference("HomeownerUsers");
user.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()){
String establishmentname=ds.child("Establishment Name").getValue().toString();
String address=ds.child("Address").getValue().toString();
String contact=ds.child("Contact").getValue().toString();
String availability=ds.child("Availablility").getValue().toString();
String price=ds.child("Price").getValue().toString();
String type=ds.child("Type").getValue().toString();
String condition=ds.child("Conditions").getValue().toString();
String ownername=ds.child("Owner Name").getValue().toString();
establishmentdisplay.setText(establishmentname);
addressdisplay.setText(address);
contactdisplay.setText(contact);
availabilitydisplay.setText(availability);
pricedisplay.setText(price);
typedisplay.setText(type);
conditiondisplay.setText(condition);
ownernamedisplay.setText(ownername);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
protected void onStart() {
super.onStart();
if(mAuth.getCurrentUser() == null){
finish();
startActivity(new Intent(this,Homeownerlogin.class));
}
}
#Override
protected void onStop() {
super.onStop();
if(mAuthListener !=null){
mAuth.removeAuthStateListener(mAuthListener);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.menulogout:
FirebaseAuth.getInstance().signOut();
finish();
startActivity(new Intent(this, Homeownerlogin.class));
Toast.makeText(Profile.this,"Log out Successfully",Toast.LENGTH_SHORT).show();
}
return true;
}
#Override
public void onClick(View v) {
if (v==btnsave){
finish();
startActivity(new Intent(Profile.this,Profile.class));
}
}
}
This is my database:
You have added your firebase listener on the entire HomeownerUsers node and then you are looping through the results. Instead you should add the listener on the specific child of HomeownerUsers of the current user. And for a bit more optimisation in your code you can use the Userinformation class to retreive the data instead of retreiving each field seperatly.
So your addValueEventListener will look like this:
final DatabaseReference user = database.getReference("HomeownerUsers").child(UserUID);
user.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String establishmentname=dataSnapshot.child("Establishment Name").getValue().toString();
String address=dataSnapshot.child("Address").getValue().toString();
String contact=dataSnapshot.child("Contact").getValue().toString();
String availability=dataSnapshot.child("Availablility").getValue().toString();
String price=dataSnapshot.child("Price").getValue().toString();
String type=dataSnapshot.child("Type").getValue().toString();
String condition=dataSnapshot.child("Conditions").getValue().toString();
String ownername=dataSnapshot.child("Owner Name").getValue().toString();
establishmentdisplay.setText(establishmentname);
addressdisplay.setText(address);
contactdisplay.setText(contact);
availabilitydisplay.setText(availability);
pricedisplay.setText(price);
typedisplay.setText(type);
conditiondisplay.setText(condition);
ownernamedisplay.setText(ownername)
}
}
More information can be found in the firebase docs.
this is my first post here, so any guidance at all is appreciated.
I'm having an issue when others download my app. It causes the App to crash on launch. It works perfectly when I install updates and seems to be an issue stemming from users not having a Firebase UID created when first launching.
Here is Main Activity Code:
package com.example.android.cellavino;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.android.cellavino.PojoDirectory.UI2.UserDetailsPojo;
import com.example.android.cellavino.UserInterface.WineAdapter;
import com.example.android.cellavino.UserInterface2.WineDetails.CreateNewWine;
import com.example.android.cellavino.UserInterface2.CreateTasting.MyTastings;
import com.example.android.cellavino.UserInterface2.EditProfile.EditProfile;
import com.example.android.cellavino.UserInterface2.JoinTasting.JoinTasting;
import com.example.android.cellavino.UserInterface2.WineDetails.MyWinesList;
import com.example.android.cellavino.Utils.Constants;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.client.ValueEventListener;
import com.firebase.ui.auth.AuthUI;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ServerValue;
import com.google.firebase.remoteconfig.FirebaseRemoteConfig;
import com.google.firebase.storage.FirebaseStorage;
import java.util.Arrays;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private static final String LOG_TAG = MainActivity.class.getSimpleName();
public static final String ANONYMOUS = "anonymous";
public static final int RC_SIGN_IN = 1;
public String mUsername;
private FirebaseAuth mFirebaseAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference mWineDatabaseReference;
private DatabaseReference mUserDatabaseReference;
private DatabaseReference mMyWinesReference;
private ChildEventListener mChildEventListener;
private FirebaseRemoteConfig mFirebaseRemoteConfig;
private FirebaseStorage mFirebaseStorage;
private WineAdapter mWineAdapter;
private ListView mWineListView;
private RecyclerView mWineRecyclerView;
private RecyclerView.Adapter mAdapter;
private ProgressBar mProgressBar;
private RecyclerView.LayoutManager mLayoutManager;
private DrawerLayout mNavigationDrawerLayout;
private ActionBarDrawerToggle mActionBarDrawerToggle;
private ListView mWineInformation;
private TextView mWineName;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private ListView mDrawerList;
private String[] mMenuOptions;
private Uri userProfilePic;
private TextView mUsernameTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setContentView(R.layout.my_wines_list);
//setContentView(R.layout.activity_container);
//getSupportFragmentManager().beginTransaction().replace(R.id.container, new MyWinesListFragment()).commit();
//Initialise Firebase
Firebase.setAndroidContext(this);
mUsername = ANONYMOUS;
//mTitle = mDrawerTitle = getTitle();
mFirebaseDatabase = FirebaseDatabase.getInstance();
mFirebaseAuth = FirebaseAuth.getInstance();
mFirebaseStorage = FirebaseStorage.getInstance();
mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
//WineDatabase in Firebase initialisation
mWineDatabaseReference = mFirebaseDatabase.getReference().child("Wine Details");
mUserDatabaseReference = mFirebaseDatabase.getReference().child("Users");
mMyWinesReference = mFirebaseDatabase.getReference().child("Users").child("myWines");
//initialising the views
//ListView mWineListView = (ListView) findViewById(R.id.wineListView);
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
//user is signed in
onSignedInInialise(user.getDisplayName());
} else {
//user is signed out
onSignedOutCleanup();
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setIsSmartLockEnabled(false)
.setProviders(Arrays.asList(
new AuthUI.IdpConfig.Builder(AuthUI.EMAIL_PROVIDER).build(),
new AuthUI.IdpConfig.Builder(AuthUI.GOOGLE_PROVIDER).build()))
.build(),
RC_SIGN_IN);
}
}
};
//add code that will bring up the Add_Wine screen when a user clicks on the floating action button for addwine.
FloatingActionButton addWineFab = (FloatingActionButton) findViewById(R.id.addWineFab);
addWineFab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, CreateNewWine.class);
startActivity(intent);
}
});
//initialise view_my_wines button click listener
Button viewMyWinesButton = (Button) findViewById(R.id.view_my_wines);
viewMyWinesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, MyWinesList.class);
startActivity(intent);
}
});
//initialise edit_profile button click listener
Button editProfileButton = (Button) findViewById(R.id.edit_profile);
editProfileButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, EditProfile.class);
startActivity(intent);
}
});
//initialise edit_profile button click listener
Button createTastingButton = (Button) findViewById(R.id.create_tasting);
createTastingButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, MyTastings.class);
startActivity(intent);
}
});
//initialise edit_profile button click listener
Button joinTastingButton = (Button) findViewById(R.id.join_tasting);
joinTastingButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, JoinTasting.class);
startActivity(intent);
}
});
FirebaseUser user = mFirebaseAuth.getCurrentUser();
String userName = user.getDisplayName();
if (user != null) {
TextView mUsernameTextView = (TextView) findViewById(R.id.user_name);
mUsernameTextView.setText(userName);
} else {
TextView mUsernameTextView = (TextView) findViewById(R.id.user_name);
mUsernameTextView.setVisibility(View.GONE);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
if (resultCode == RESULT_OK) {
FirebaseUser user = mFirebaseAuth.getCurrentUser();
String uid = user.getUid();
String userName = user.getDisplayName();
String userEmail = user.getEmail();
Uri userProfilePic = user.getPhotoUrl();
createUserInFirebaseHelper(uid, userName, userEmail);
Toast.makeText(MainActivity.this, "Hello " + userName + "!", Toast.LENGTH_SHORT).show();
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(MainActivity.this, "Sign in cancelled", Toast.LENGTH_SHORT).show();
finish();
}
}
}
private void createUserInFirebaseHelper(String uid, String userName, String userEmail) {
final String mUserName = userName;
final String mUserEmail = userEmail;
final Firebase userDetailLocation = new Firebase(Constants.FIREBASE_URL_LOCATION_USERS).child(uid);
//See if there is already a user (for example, if they already logged in with an associated google account
userDetailLocation.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(com.firebase.client.DataSnapshot dataSnapshot) {
// If there is no user, make one
if (dataSnapshot.getValue() == null) {
//Set raw version of date to the ServerValue.TIMESTAMP value and save into dateCreatedMap
HashMap<String, Object> timestampJoined = new HashMap<>();
timestampJoined.put(Constants.FIREBASE_PROPERTY_TIMESTAMP, ServerValue.TIMESTAMP);
UserDetailsPojo newUser = new UserDetailsPojo(mUserName, mUserEmail, timestampJoined);
userDetailLocation.setValue(newUser);
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Log.d(LOG_TAG, getString(R.string.log_error_occurred) + firebaseError.getMessage());
}
});
}
//When the app comes back from background state etc
#Override
protected void onResume() {
super.onResume();
mFirebaseAuth.addAuthStateListener(mAuthStateListener);
}
//When the app goes to background state
#Override
protected void onPause() {
super.onPause();
if (mAuthStateListener != null) {
mFirebaseAuth.removeAuthStateListener(mAuthStateListener);
}
detachDatabaseReadListener();
//mWineAdapter.clear();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_navigation_drawer, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
//if (mActionBarDrawerToggle.onOptionsItemSelected(item)) {
// return true;
//}
switch (item.getItemId()) {
case R.id.sign_out_menu:
//sign out
AuthUI.getInstance().signOut(this);
return true;
/*
case R.id.menu_add_wine:
//add wine
Intent intent = new Intent(MainActivity.this, AddWine.class);
startActivity(intent);
return true;
case R.id.view_my_wines:
//view the working wine list Andrews Wines
Intent intent2 = new Intent(MainActivity.this, MyWinesList.class);
startActivity(intent2);
return true;
case R.id.test_option:
//view the test screens for Andrews Wines
Intent intent3 = new Intent(MainActivity.this, Login.class);
startActivity(intent3);
return true;
*/
default:
return super.onOptionsItemSelected(item);
}
}
private void onSignedInInialise(String username) {
mUsername = username;
//attachDatabaseReadListener();
//this code adds a new user name each time it logs in.
//mUserDatabaseReference.push().setValue(username);
}
private void onSignedOutCleanup() {
mUsername = ANONYMOUS;
//mWineAdapter.clear();
detachDatabaseReadListener();
}
/*
private void attachDatabaseReadListener() {
if (mChildEventListener == null) {
mChildEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
WineDetails wineDetails = dataSnapshot.getValue(WineDetails.class);
//mWineAdapter.add(wineDetails);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
mWineDatabaseReference.addChildEventListener(mChildEventListener);
}
}
*/
private void detachDatabaseReadListener() {
if (mChildEventListener != null) {
mWineDatabaseReference.removeEventListener(mChildEventListener);
mChildEventListener = null;
}
}
private void initializeScreen(View rootView) {
mWineInformation = (ListView) rootView.findViewById(R.id.wine_list_item_details);
mWineName = (TextView) rootView.findViewById(R.id.wine_name);
}
}
How can I adjust it so it checks to see if a user has a profile and if not directs them to the login page?
Thanks in advance.
I figured it out. I was calling getDisplayName() prior to checking authentication.
Thanks for the pointers in how to post a question. I waited 6 months before posting one as I wasn't really sure how/what to ask. Now I know. :)
I am making a chat app using Firebase. I have created a class called Chat Activity where the user can send or receive messages. Along with this, I am creating Notifications. For the initial stage, I am building the notification as soon as the ChatActivity is being created.
The content of the body is the last message that was sent. But when I sent the title of the notification to the name of the user, it does not display the title. I am obtaining the name of the user using a new function called "getNameFromRoll()". But this also returns null.
When a user signs up in the app, not only it is registered in the firebase users list, but also in a child in the database called "students" in an inner child called "profiles". getNameFromRoll() reads data from this child.
Here's the code:
ChatActivity:
package com.app.shubhamjhunjhunwala.heritagecompanion_students;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.NotificationCompat;
import android.support.v4.graphics.BitmapCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.ForwardingListener;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.security.PublicKey;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
/**
* Created by shubham on 03/02/17.
*/
public class ChatActivity extends AppCompatActivity {
public String chatName;
public String chatRoll;
public String messageText;
public String time;
public String name;
public String senderRoll;
public String mId;
public List<Messages> mMessages;
public List<Chats> mChats;
public RecyclerView mMessagesListView;
public MessageAdapter mMessageAdapter;
public EditText mMessageEditText;
public FloatingActionButton mSendFAB;
public FirebaseDatabase mDatabase;
public DatabaseReference mSenderDatabaseReference;
public DatabaseReference mRecieverDatabaseReference;
public DatabaseReference mRecieverChatsDatabaseReference;
public DatabaseReference mUsersDatabaseReference;
public ChildEventListener mChildEventListener;
public ChildEventListener mChatsChildEventListener;
public ChildEventListener mUserChildEventListener;
public Intent mServiceIntent;
public String IS_NAME_KEY = "com.app.shubhamjhunjhunwala.heritagecompanion_students.IS_NAMEKEY";
public String IS_MESSAGE_KEY = "com.app.shubhamjhunjhunwala.heritagecompanion_students.IS_MESSAGEKEY";
public ChatActivity() {
}
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
final Intent intent = getIntent();
Bundle extras = intent.getExtras();
chatName = intent.getStringExtra(ChatsActivity.EXTRA_NAME);
chatRoll = intent.getStringExtra(ChatsActivity.EXTRA_ROLL);
setTitle(chatName);
SharedPreferences sharedPreferences = getSharedPreferences("HCS", 0);
senderRoll = sharedPreferences.getString(AuthenticationActivity.ROLL_SHARED_PREFERENCE_KEY, "");
mDatabase = FirebaseDatabase.getInstance();
mSenderDatabaseReference = mDatabase.getReference().child("chats").child(senderRoll).child("messages").child(chatRoll);
mRecieverDatabaseReference = mDatabase.getReference().child("chats").child(chatRoll).child("messages").child(senderRoll);
mRecieverChatsDatabaseReference = mDatabase.getReference().child("chats").child(chatRoll);
mUsersDatabaseReference = mDatabase.getReference().child("students").child("profiles");
mMessageEditText = (EditText) findViewById(R.id.message_edit_text);
mSendFAB = (FloatingActionButton) findViewById(R.id.send_fab);
mMessages = new ArrayList<>();
mChats = new ArrayList<>();
mMessagesListView = (RecyclerView) findViewById(R.id.messages_list_view);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
mMessagesListView.setLayoutManager(layoutManager);
mMessageAdapter = new MessageAdapter(mMessages, senderRoll, chatRoll);
mMessagesListView.setAdapter(mMessageAdapter);
mSendFAB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
messageText = mMessageEditText.getText().toString().trim();
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
time = df.format(c.getTime());
if (messageText != "") {
Messages message = new Messages(messageText, time, senderRoll, chatRoll, mId);
mSenderDatabaseReference.push().setValue(message);
mRecieverDatabaseReference.push().setValue(message);
}
mMessageEditText.setText("");
}
});
message();
}
public void message() {
mChildEventListener = new ChildEventListener() {
int n;
Chats chat;
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if (dataSnapshot != null && dataSnapshot.getValue() != null) {
Messages messages = dataSnapshot.getValue(Messages.class);
mMessages.add(messages);
mMessagesListView.scrollToPosition(mMessages.size() - 1);
mMessageAdapter.notifyItemInserted(mMessages.size() - 1);
notificationBuilder(ChatActivity.this, messages.getSender(), messages.getMessage());
n = setNewChatHeader();
if (n == 1) {
chat = new Chats(chatName, chatRoll);
mRecieverChatsDatabaseReference.setValue(chat);
}
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
mSenderDatabaseReference.addChildEventListener(mChildEventListener);
}
public int setNewChatHeader() {
mChatsChildEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if (dataSnapshot != null && dataSnapshot.getValue() != null) {
Chats chats = dataSnapshot.getValue(Chats.class);
if (chats.getName() != null) {
mChats.add(chats);
}
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
mRecieverChatsDatabaseReference.addChildEventListener(mChatsChildEventListener);
if (mChats.size() != 0) {
for (int i = 0; i < mChats.size(); i++) {
Chats chat = mChats.get(i);
String name = chat.getName();
if (name.equals(chatName)) {
return 1;
}
}
}
return 0;
}
public String getSenderRoll() {
return senderRoll;
}
public void notificationBuilder(Context context, String name, String message) {
getNameFromRollNumber(name);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setColor(getResources().getColor(R.color.colorPrimary))
.setSmallIcon(R.drawable.ic_message_notification_icon)
.setLargeIcon(largeIcon(context))
.setContentTitle(this.name)
.setContentText(message)
.setStyle(new NotificationCompat.BigTextStyle().bigText(message))
.setDefaults(Notification.DEFAULT_VIBRATE)
.setAutoCancel(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
mBuilder.setPriority(Notification.PRIORITY_HIGH);
}
Intent resultIntent = new Intent(this, ChatActivity.class);
PendingIntent resultPendingIntent = PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
int mNotificationId = 001;
NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotifyMgr.notify(mNotificationId, mBuilder.build());
}
public Bitmap largeIcon(Context context) {
Resources res = context.getResources();
Bitmap largeIcon = BitmapFactory.decodeResource(res, R.mipmap.ic_launcher);
return largeIcon;
}
public void getNameFromRollNumber (String roll) {
mUsersDatabaseReference = mUsersDatabaseReference.child(roll);
mUserChildEventListener = new ChildEventListener() {
ChatActivity chatActivity = new ChatActivity();
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
UserDetails userDetails = dataSnapshot.getValue(UserDetails.class);
chatActivity.setName(userDetails.getName());
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
mUsersDatabaseReference.addChildEventListener(mUserChildEventListener);
Toast.makeText(ChatActivity.this, name, Toast.LENGTH_SHORT).show();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
UserDetails.class:
package com.app.shubhamjhunjhunwala.heritagecompanion_students;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
/**
* Created by shubham on 23/01/17.
*/
public class UserDetails {
UserDetails() {}
public String name;
public String email;
public String password;
public String phone;
public String roll;
public String sharingKey;
public String department;
public String year;
public String section;
public UserDetails(String name, String email, String password, String phone, String roll, String sharingKey, String department, String year, String section) {
this.name = name;
this.email = email;
this.password = password;
this.phone = phone;
this.roll = roll;
this.sharingKey = sharingKey;
this.department = department;
this.year = year;
this.section = section;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getRoll() {
return roll;
}
public void setRoll(String roll) {
this.roll = roll;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public String getSection() {
return section;
}
public void setSection(String section) {
this.section = section;
}
public String getSharingKey() {
return sharingKey;
}
public void setSharingKey(String sharingKey) {
this.sharingKey = sharingKey;
}
}
The sample of the database Structure:
heritage-companion-students
chats
students
-Kcgc88CAieCWCWPvA8D
-KcgcNrZj2Saueyaejw5
-Kcgce-x43DaaYiHjTpK
-Kcgcqh1uJ8E_KgKDcq0
-Kcgd36xoBcdsJriqMjS
-KcgdHY9CxaoCQ9poEna
profiles
1657099
1657102
1657103
1657108
-Kcgc87aRCL_D1KXJypP
department:
email:
name:
password:
phone:
roll:
sharingKey:
1657113
1657120
Whenever I click on the SAVE Button to save the name and number, the skills field is being overwritten.
Here the image of Activity while storing details
Also please help me to get the skills as a list instead of creating new skilladd every time. Also new skills must be appended to the list without overwriting.
/**** ACCOUNT.JAVA ****/
package com.coginitoamicis.coginitoamicis;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class Account extends AppCompatActivity implements View.OnClickListener {
private EditText accname;
private EditText accnumb;
private EditText accskill;
private Button accsave;
private Button accskilladd;
private DatabaseReference databaseReference;
private FirebaseAuth firebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account);
firebaseAuth = FirebaseAuth.getInstance();
if (firebaseAuth.getCurrentUser()==null){
finish();
startActivity(new Intent(getApplicationContext(), LoginActivity.class));
}
databaseReference = FirebaseDatabase.getInstance().getReference();
accname = (EditText) findViewById(R.id.accname);
accnumb = (EditText) findViewById(R.id.accnumb);
accsave = (Button) findViewById(R.id.accsave);
accskill = (EditText) findViewById(R.id.accskill);
accskilladd = (Button) findViewById(R.id.accskilladd);
accsave.setOnClickListener(this);
accskilladd.setOnClickListener(this);
}
private void userdatasave(){
String name = accname.getText().toString().trim();
String numb = accnumb.getText().toString().trim();
if(TextUtils.isEmpty(name)){
//name is empty
Toast.makeText(this,"Please Enter your Name",Toast.LENGTH_SHORT).show();
return;
}
if(TextUtils.isEmpty(numb)){
//number is empty
Toast.makeText(this,"Please Enter your Mobile Number",Toast.LENGTH_SHORT).show();
return;
}
UserInformation userInformation = new UserInformation(name, numb);
FirebaseUser user =firebaseAuth.getCurrentUser();
databaseReference.child(user.getUid()).setValue(userInformation);
Toast.makeText(this,"Information Saved",Toast.LENGTH_SHORT).show();
}
private void skilldatasave(){
String skill = accskill.getText().toString().trim();
if(TextUtils.isEmpty(skill)){
//skills is empty
Toast.makeText(this,"Enter Skill to Proceed",Toast.LENGTH_SHORT).show();
return;
}
Skilladd skilladds = new Skilladd(skill);
FirebaseUser user =firebaseAuth.getCurrentUser();
databaseReference.child(user.getUid()).push().setValue(skilladds);
Toast.makeText(this,"Skills Added Successfully",Toast.LENGTH_SHORT).show();
}
#Override
public void onClick(View view) {
if (view == accsave){
userdatasave();
}
if (view == accskilladd){
skilldatasave();
}
}
}
/**** USERINFORMATION.JAVA ****/
package com.coginitoamicis.coginitoamicis;
public class UserInformation {
public String name;
public String numb;
public UserInformation(String name, String numb){
this.name = name;
this.numb = numb;
}
}
/**** SKILLADD.JAVA ****/
package com.coginitoamicis.coginitoamicis;
public class Skilladd {
public String skill;
public Skilladd(String skill){
this.skill = skill;
}
}
Use Push()
Firebase newsPush = new Firebase(Config.FIREBASE_URL);
final News news = new News();
news.setNewsTitle(newsTitleString);
news.setNewsDetails(newsDetailsString);
newsPush.push().setValue(news);
Create Getters and Setters for Object
public class News implements Serializable {
private String newsTitle;
private String newsDetails;
private String newsDate;
private String newsPicUrl;
/*news Model to get and set news data*/
public String getNewsTitle() {
return newsTitle;
}
public void setNewsTitle(String newsTitle) {
this.newsTitle = newsTitle;
}
public String getNewsDetails() {
return newsDetails;
}
public void setNewsDetails(String newsDetails) {
this.newsDetails = newsDetails;
}
Use this on oncreate
keysArray = new ArrayList<>();
valuesAdapter = new ArrayAdapter<String> (this,android.R.layout.simple_list_item_1, android.R.id.text1, displayArray);
listView.setAdapter(valuesAdapter);
listView.setOnItemClickListener(itemClickListener);
rootRef = FirebaseDatabase.getInstance().getReference();
rootRef.addChildEventListener(childEventListener);
save.setOnClickListener(this);
here i use this code onSAve click:
private void save(String name, String message) {
rootRef.child(name).setValue(message, new CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
nameEditText.setText("");
messageEditText.setText("");
hideProgressBar();
}
});
}
and here use child listner :
ChildEventListener childEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Log.d(TAG, dataSnapshot.getKey() + ":" + dataSnapshot.getValue().toString());
String keyAndValue = "Name: " + dataSnapshot.getKey().toString() + "\t Messsage: " + dataSnapshot.getValue().toString();
displayArray.add(keyAndValue);
keysArray.add(dataSnapshot.getKey().toString());
updateListView();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
String changedKey = dataSnapshot.getKey();
int changedIndex = keysArray.indexOf(changedKey);
String keyAndValue = "Name: " + dataSnapshot.getKey().toString() + "\t Messsage: " + dataSnapshot.getValue().toString();
displayArray.set(changedIndex, keyAndValue);
updateListView();
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
String deletedKey = dataSnapshot.getKey();
int removedIndex = keysArray.indexOf(deletedKey);
keysArray.remove(removedIndex);
displayArray.remove(removedIndex);
updateListView();
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
Log.d(TAG, dataSnapshot.getKey() + ":" + dataSnapshot.getValue().toString());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};