Data is not stored in Firebasae Database - android

When the "Add Item to the menu" button is clicked it will show "item added" which means it should be added to my firebase database, but when I check it nothing is showing meaning it was not stored. :(
Here are my codes
public class addItem extends AppCompatActivity{
private Button btnAdd;
private EditText name,desc,price;
private StorageReference storageReference = null;
private DatabaseReference mRef;
private FirebaseDatabase firebaseDatabase;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_item);
name = (EditText) findViewById(R.id.txtName);
desc = (EditText) findViewById(R.id.txtDescription);
price = (EditText) findViewById(R.id.txtPrice);
storageReference = FirebaseStorage.getInstance().getReference();
mRef = FirebaseDatabase.getInstance().getReference("Item");
}
public void addItemToMenu(View v)
{
final String name_text = name.getText().toString().trim();
final String desc_text = desc.getText().toString().trim();
final String price_text = price.getText().toString().trim();
if (!TextUtils.isEmpty(name_text) && !TextUtils.isEmpty(desc_text) && !TextUtils.isEmpty(price_text))
{
Toast.makeText(addItem.this, "Item Added", Toast.LENGTH_SHORT).show();
final DatabaseReference newPost = mRef.push();
newPost.child("name").setValue(name_text);
newPost.child("desc").setValue(desc_text);
newPost.child("price").setValue(price_text);
}

check the rules for firebase in your firebase console and change rules according to your scenario..

Change your database rules to:
{
"rules": {
".read": true,
".write": true
}
}

Related

When I click on the Cardview how to keep it in its ON state with the same color until I click it OFF?

I have a card view with on-click listener on it. As I click on it the color of card view get change which means it is ON. But as I move on any another activity the color of card view get change. I do not want that color to get change. Help me out.
Code of card view...
private void setToggleEvent(GridLayout mainGrid) {
final CardView bulb=(CardView)mainGrid.getChildAt(0);
bulb.setCardBackgroundColor(Color.parseColor("#404040"));
bulb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(bulb.getCardBackgroundColor().getDefaultColor()!=Color.parseColor("#FFD100"))
{
bulb.setCardBackgroundColor(Color.parseColor("#FFD100"));
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("BULB");
myRef.setValue("1");
}
else
{
bulb.setCardBackgroundColor(Color.parseColor("#404040"));
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("BULB");
myRef.setValue("0");
}
}
});
try this :
final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sharedPreferences.edit();
String color = sharedPreferences.getString("MY_KEY", "#fcfcfc");//#fcfcfc is defualt value!
bulb.setCardBackgroundColor(Color.parseColor(color));
bulb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (bulb.getCardBackgroundColor().getDefaultColor() != Color.parseColor("#fcfcfc")) {
bulb.setCardBackgroundColor(Color.parseColor("#fcfcfc"));
sharedPreferences.edit().putString("MY_KEY", "#fcfcfc").apply();
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("BULB");
myRef.setValue("1");
} else {
bulb.setCardBackgroundColor(Color.parseColor("#404040"));
sharedPreferences.edit().putString("MY_KEY", "#404040").apply();
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("BULB");
myRef.setValue("0");
}
}
});

Save multiple data with same uid to Firebase database

I'm working in Android Studio on an app that uses Firebase for signing in and store data to its realtime database.
I'm using the default firebase database rules, so only authenticated users can write/read in the database.
I've an activity (AddMarker) that saves two editText values and one LatLong value (this one from another activity) to the database.
The code is actually working and i can see data stored in it in this way:
DB structure
The problem is that everytime i save (in AddMarker Activity), the previous data linked to that id, gets replaced by the new one.
Instead i would like to store in the DB multiple values with the same id like this for example:
DB structure 2
This is my code
public class AddMarker extends AppCompatActivity implements View.OnClickListener {
//Save flag
public static boolean isSaved;
//Database
private DatabaseReference databaseReference;
FirebaseAuth firebaseAuth;
private FirebaseAuth mAuth;
//UI
private EditText tipo, marca;
private Button saveMarker;
public LatLng ll;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_marker);
//DB
mAuth = FirebaseAuth.getInstance();
databaseReference = FirebaseDatabase.getInstance().getReference();
//Initialize views
tipo = (EditText) findViewById(R.id.type);
marca = (EditText) findViewById(R.id.specInfo);
saveMarker = (Button) findViewById(R.id.save_btn);
//Initialize isSaved
isSaved = false;
//Set button listener
saveMarker.setOnClickListener(this);
//get Position
ll = getIntent().getParcelableExtra("POSITION");
}
private MarkerOptions saveMarkerInfo(){
String tipo_str = tipo.getText().toString().trim();
String marca_str = marca.getText().toString().trim();
LatLng pos = ll;
MarkerInfo markerInfo = new MarkerInfo(tipo_str,marca_str, pos);
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
MarkerOptions marker = new MarkerOptions()
.position(ll)
.anchor(0.0f, 1.0f)
.title("prova")
//Add data to DB
databaseReference.child(user.getUid()).setValue(markerInfo);
Toast.makeText(this,"infos saved",Toast.LENGTH_LONG).show();
finish();
return marker;
}
#Override
public void onClick(View v) {
if(v == saveMarker){
isSaved = true;
MarkerOptions mo=saveMarkerInfo();
MainActivity.mMap.addMarker(mo);
}
}
}
you cannot create two nodes with same Id instead you can create a nested structure inside each userId. and setValues accordingly like this.
databaseReference.child(user.getUid()).push().setValue(markerInfo);
this will create childs under singleUserId with your multiple data
for more you can refer this

Adding Social Media Share Logic From Firebase in Android

I am building an android instagram clone app with Firebase. I have enabled social media sharing buttons in my app to share the contents of a story via Facebook, email, WhatsApp, etc but don't know how to go about it.
Take a look at what I've tried:
public class InstacloneApp extends AppCompatActivity {
private RelativeLayout relativeLayout;
private ImageView postCoverImg, userPhotoUrl;
private TextView post_Title, post_Descpn, post_Author, postDate;
private Button commentsBtn;
private FloatingActionButton shareFAB;
private String post_details = null;
private FirebaseAuth mAuth;
private DatabaseReference postRef;
private Context mCtx = this;
private String uid_post = null;
private ScrollView scrollView;
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insta_clone_app);
relativeLayout = (RelativeLayout) findViewById(R.id.activity_blog_posts_view);
scrollView = (ScrollView) findViewById(R.id.scrollView);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("");
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
post_details = getIntent().getExtras().getString("post+key");
postCoverImg = (ImageView) findViewById(R.id.post_Backdrop);
post_Title = (TextView) findViewById(R.id.post_title);
post_Descpn = (TextView) findViewById(R.id.post_description_long);
post_Author = (TextView) findViewById(R.id.authorTV);
userPhotoUrl = (ImageView) findViewById(R.id.author_photo);
postDate = (TextView) findViewById(R.id.post_date);
shareFAB = (FloatingActionButton) findViewById(R.id.shareFAB);
commentsBtn = (Button) findViewById(R.id.commentsBtn);
mAuth = FirebaseAuth.getInstance();
postRef = FirebaseDatabase.getInstance().getReference().child("Blog").child("All_Posts");
postRef.keepSynced(true);
postRef.child(post_details.toString()).addValueEventListener(new ValueEventListener() { // this is to retrieve and view the blog post data
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String title_post = (String) dataSnapshot.child("postTitle").getValue();
String desc_post = (String) dataSnapshot.child("full_postDesc").getValue();
String backdrop_post = (String) dataSnapshot.child("postImage").getValue();
String date_post = (String) dataSnapshot.child("postDate").getValue();
uid_post = (String) dataSnapshot.child("uid").getValue();
post_Title.setText(title_post);
post_Descpn.setText(desc_post);
postDate.setText(date_post);
Glide.with(mCtx).load(backdrop_post).into(postCoverImg);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
shareFAB.setOnClickListener(new View.OnClickListener() { // my implemented share action
#Override
public void onClick(View view) {
String content = post_details;
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("*/*");
shareIntent.putExtra(Intent.EXTRA_TEXT,content);
startActivity(Intent.createChooser(shareIntent,"Share With"));
}
});
Since your sharing the post content try changing your
from:
intent.setType("*/*");
To:
intent.setType("text/plain");
I assume you want to share Image and Text(description or some other details) both for that you can have a look at this question
If you want to add a link to your app, something like in apps like Reddit/Instagram have a look at this question
You can combine both to share the Image and Text (url + small description/username) to any app that accepts it like WhatsApp
Hope it helped!
You should try
shareIntent.setType("text/plain");
instead of
shareIntent.setType("*/*");

The email address is badly formatted Firebase

hi i am working on a android project where i am using firebase as back-end and i am building a signup and login form . When ever i sign up the code is working well and . When i try to retrieve it using "signInWithEmailAndPassword i am getting the fallowing error. The email address is badly formatted Firebase`
login Activity
public class LoginActivity extends AppCompatActivity {
private EditText mLoginEmailField;
private EditText mloginPassField;
private Button mLoginbtn;
private Button mNewAccountbtn;
private DatabaseReference mDatabaseRefrence;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mAuth = FirebaseAuth.getInstance();
mLoginEmailField = (EditText) findViewById(R.id.loginEmailField);
mloginPassField = (EditText) findViewById(R.id.loginPasswordField);
mLoginbtn = (Button) findViewById(R.id.loginBtn);
mNewAccountbtn = (Button) findViewById(R.id.newAccountbtn);
mDatabaseRefrence = FirebaseDatabase.getInstance().getReference().child("Users");
mNewAccountbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent rigisterIntent = new Intent(LoginActivity.this,RigisterActivity.class);
rigisterIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(rigisterIntent);
}
});
mLoginbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckLogin();
}
});
}
private void CheckLogin() {
String email = mloginPassField.getText().toString().trim();
String pass = mloginPassField.getText().toString().trim();
if(!TextUtils.isEmpty(email) && !TextUtils.isEmpty(pass)){
mAuth.signInWithEmailAndPassword(email,pass).addOnCompleteListener(this,new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
CheackUserExsists();
}else{
System.out.println("Sign-in Failed: " + task.getException().getMessage());
Toast.makeText(LoginActivity.this,"Erorr Login",Toast.LENGTH_LONG).show();
}
}
});
}
}
private void CheackUserExsists() {
final String user_id = mAuth.getCurrentUser().getUid();
mDatabaseRefrence.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChild(user_id)){
Intent MainIntent = new Intent(LoginActivity.this,MainActivity.class);
MainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(MainIntent);
}else
{
Toast.makeText(LoginActivity.this,"You need to setup your Account.. ",Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
Rigister Actvity
public class RigisterActivity extends AppCompatActivity {
private EditText mNameField;
private EditText mPassField;
private EditText mEmailField;
private Button mRigisterbtn;
private ProgressDialog mProgres;
private DatabaseReference mDatabase;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rigister);
mDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
mAuth = FirebaseAuth.getInstance();
mProgres = new ProgressDialog(this);
mNameField = (EditText) findViewById(R.id.nameField);
mPassField = (EditText) findViewById(R.id.passFiled);
mEmailField = (EditText) findViewById(R.id.emailField);
mRigisterbtn = (Button) findViewById(R.id.rigisterbtn);
mRigisterbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StartRigister();
}
});
}
private void StartRigister() {
final String name = mNameField.getText().toString().trim();
String pass = mPassField.getText().toString().trim();
String email = mEmailField.getText().toString().trim();
if(!TextUtils.isEmpty(name) && !TextUtils.isEmpty(pass) && !TextUtils.isEmpty(email)){
mProgres.setMessage("Signing Up... ");
mProgres.show();
mAuth.createUserWithEmailAndPassword(email,pass).addOnCompleteListener(this,new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
String user_id = mAuth.getCurrentUser().getUid();
DatabaseReference CurentUser_db = mDatabase.child(user_id);
CurentUser_db.child("name").setValue(name);
CurentUser_db.child("image").setValue("defalut");
mProgres.dismiss();
Intent mainIntent = new Intent(RigisterActivity.this, MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(mainIntent);
}
}
});
}
}
}
I have made sure that i have setup email and password active in the auth section of firebase.
still firebase giving me the following error.
Your code to set email is incorrect. You are setting email to the value of the EditText for password.
In method CheckLogin(), change:
String email = mloginPassField.getText().toString().trim();
to:
String email = mLoginEmailField .getText().toString().trim();
Simply use Edittext named as Email and Password you need not do anything.
the error comes up only if you use plaintext for both...
I faced this problem recently, possible solutions are :
Check the inputType of your EditText Field.
ADD this attribute to your EditText
android:inputType="textEmailAddress"
In Activity class, it should look like if u are using TextInputLayout instead of editText
mDisplayName=(TextInputLayout) findViewById(R.id.reg_name);
mDisplayEmail=(TextInputLayout)findViewById(R.id.reg_email);
mDisplayPassword=(TextInputLayout)findViewById(R.id.reg_password);
String name = mDisplayName.getEditText().getText().toString();
String email = mDisplayEmail.getEditText().getText().toString();
String password = mDisplayPassword.getEditText().getText().toString();`
Remove whitespaces from email text it worked for me. by using trim() method you can remove spaces.
The error popped for me due to my silly action of using "tab" to go to the next text field. Don't use "tab" for it, instead use your mouse to move to the next text field. Worked for me.
What helped me resolve this issue is to put the android:id into the correct place.
If you are using Material design, there are two parts of your text input, the layout and the actual functional part.
If you put the ID into the layout, you'll only be able to access editText property in the activity class, but if you put it in the functional part, you'll be able to access .text or getText() as someone above has stated.
Change
String pass = mloginPassField.getText().toString().trim();
mAuth.signInWithEmailAndPassword(email,pass)
to
String password = mloginPassField.getText().toString().trim();
mAuth.signInWithEmailAndPassword(email,password)
Your code to set email is incorrect.
Perhaps a space was used as the last letter.
final User? user = (await _auth.signInWithEmailAndPassword(
email: _emailController.text.toString().trim(),
password: _passwordController.text,
)).user;[![enter image description here][1]][1]

Hi! How do I store the fields and display the results on a different activity ? Please

I want the fields entered by the user to be displayed as a list view of the studentnoText and courseField in a new activity..
public class Student extends Activity {
private String totalStudents [];
private EditText studentnoText;
private EditText studentnameText;
private EditText courseField;
private Spinner departmentSpinner;
private EditText dobField;
private Button registerButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student);
studentnoText = (EditText) findViewById(R.id.studentnoText);
studentnameText = (EditText) findViewById(R.id.studentnameText);
dobField = (EditText) findViewById(R.id.dobField);
courseField = (EditText) findViewById(R.id.courseField);
departmentSpinner = (Spinner) findViewById(R.id.departmentSpinner);
registerButton = (Button) findViewById(R.id.registerButton);
}
public void registerButtonPressed (View view){
Log.v("Register","Register Pressed!");
}
}
USE PUT EXTRA TO SEND DATA
mIntent.putExtra("TEXT", studentnoText.gettext().toString());
mIntent.putExtra("TEXT_1", studentName.gettext().toString());
USE GET EXTRA TO GET DATA
String strNO,strName;
strNO= extras.getString("TEXT");
strName = extras.getString("TEXT_1");

Categories

Resources