Fix My Firebase database Chat Application - android

Hello everyone im trying to make a simple chat app using google firebase db.
im facing the problem please help me.
when i want to insert new element in child .
But it's inserting into root of database
Like blow image.
But I want to insert Like .
Here is My Activity Code
public class RoomChat extends AppCompatActivity implements View.OnClickListener{
String room_name,userName;
EditText getMessage;
TextView setMe;
Button button;
DatabaseReference root ;
private String temp_key;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_room);
button =(Button)findViewById(R.id.button);
button.setOnClickListener(this);
getMessage=(EditText)findViewById(R.id.editText);
setMe=(TextView)findViewById(R.id.textView);
room_name = getIntent().getStringExtra("Roomname");
userName =getIntent().getStringExtra("userName");
setTitle("Room -"+room_name);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.button:
goIntoChatRoom();
break;
}
}
private void goIntoChatRoom() {
root = FirebaseDatabase.getInstance().getReference().child(room_name);
Log.i("RoomChat",root.getRef().child(room_name).toString());
Map<String,Object> map = new HashMap<String,Object>();
temp_key = root.push().getKey();
Log.i("RoomChat","tempkey :"+temp_key);
root.updateChildren(map);
DatabaseReference message = FirebaseDatabase.getInstance().getReference().child(temp_key);
Log.i("RoomChat",message.toString());
Map<String,Object> chatRoomMap2 = new HashMap<String,Object>();
chatRoomMap2.put("name",userName);
chatRoomMap2.put("message",getMessage.getText().toString());
message.updateChildren(chatRoomMap2);
}
}

try to change this piece of line :
root = FirebaseDatabase.getInstance().getReference().child(room_name);
to
root = FirebaseDatabase.getInstance().getReference(room_name);

Related

I want to update my document fields in android studio

Here is Code
holder.btnEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final DialogPlus dialogPlus=DialogPlus.newDialog(holder.btnEdit.getContext())
.setContentHolder(new ViewHolder(R.layout.update_popup))
.setExpanded(Boolean.parseBoolean("true"),1200)
.create();
//dialogPlus.show();
View v =dialogPlus.getHolderView();
EditText name=v.findViewById(R.id.editName);
EditText fname=v.findViewById(R.id.editFName);
EditText Department=v.findViewById(R.id.editdepartment);
EditText RollNo=v.findViewById(R.id.editroll);
EditText phone=v.findViewById(R.id.editphone);
EditText email=v.findViewById(R.id.editEmail);
EditText address=v.findViewById(R.id.editAddress);
EditText password=v.findViewById(R.id.editPassword);
Button btnUpdate = v.findViewById(R.id.btnUpdate);
name.setText(student.getName());
fname.setText(student.getFName());
Department.setText(student.getDepartment());
RollNo.setText(student.getRollno());
phone.setText(student.getPhone());
email.setText(student.getEmail());
address.setText(student.getAddress());
password.setText(student.getPass());
dialogPlus.show();
btnUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Map<String,Object> map = new HashMap<>();
map.put("Name",name.getText().toString());
map.put("FName",fname.getText().toString());
map.put("Department",Department.getText().toString());
map.put("Rollno",RollNo.getText().toString());
map.put("phone",phone.getText().toString());
map.put("Email",email.getText().toString());
map.put("address",address.getText().toString());
map.put("pass",password.getText().toString());
FirebaseUser user = mAuth.getCurrentUser();
FirebaseFirestore firestore=FirebaseFirestore.getInstance();
firestore.collection("Student").document(user.getUid()).update(map)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
}
});
Like in Real time Database it would be
FirebaseDatabase.getInstance().getReference().child("Student").child(getRef(Position).key)).updateChildren(map)
How I can do it in Firestore?
It looks like you never initialize mAuth.
You probably need something like this in your onCreate:
mAuth = FirebaseAuth.getInstance();
Also see the documentation on getting started with Firebase Authentication on Android, from which that code comes.

Adding a Item to Listview

Im trying to simply add a Item to a Listview and display it. But if I add it it just shows me the path of that string istead of the tring itself. I'm sure it's a simple mistake but I cant find it.
public class zutatenHinzufuegen extends AppCompatActivity {
private ArrayList<String> zutatenliste;
private ListView zutatenView;
private ArrayAdapter<String> zutatenadapter;
private TextInputLayout zutatInput;
private TextInputLayout anzahlInput;
private int anzahlint;
private String einheitInput;
private Button hinzufuegen_button;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.zutaten_hinzufuegen_linear);
getSupportActionBar().setTitle(R.string.menu_zutaten);
// Spinner
final Spinner einheiten_spinner = (Spinner) findViewById(R.id.spinner_einheiten2);
ArrayAdapter<String> einheiten_adapter = new ArrayAdapter<String>(zutatenHinzufuegen.this,
android.R.layout.simple_list_item_1,getResources().getStringArray(R.array.einheiten));
einheiten_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
einheiten_spinner.setAdapter(einheiten_adapter);
// List
zutatInput =(TextInputLayout) findViewById(R.id.textInputZutat2);
einheitInput =(String) einheiten_spinner.getSelectedItem().toString();
anzahlInput = (TextInputLayout) findViewById(R.id.textInputAnzahl2);
try {
anzahlint = Integer.parseInt(anzahlInput.toString());
}catch (NumberFormatException nfe){}
hinzufuegen_button = findViewById(R.id.zutat_hinzufuegen_button2);
zutatenView =(ListView) findViewById(R.id.zutatenliste2);
zutatenliste= new ArrayList<>();
zutatenadapter = new ArrayAdapter<String>(this,R.layout.zutatenliste_items,R.id.textitemliste,zutatenliste);
// zutatenadapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_item, zutatenliste);
zutatenView.setAdapter(zutatenadapter);
hinzufuegen_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// hinzufuegen(v , einheiten_spinner);
ZutatClass newzutat = new ZutatClass(zutatInput.toString(),anzahlint,einheitInput);
zutatenliste.add((String) newzutat.zutat_sting);
zutatenadapter.notifyDataSetChanged();
}
});
}
}
This is what I see when i press the button a few times
I'm new to Android Studio and java so I hope it's not to much of a mess.
Thanks in advance.
First of all, you need to add Edittext inside the TextInputLayout and then get a text like this ZutatClass newzutat = new ZutatClass(zutatInput.getEditText().getText().toString(),anzahlint,einheitInput); on your on click method
I guess the issue is that you are trying to convert a TextInputLayout to string instead of getting the text from it and convert it to string , try the code below
hinzufuegen_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// hinzufuegen(v , einheiten_spinner);
ZutatClass newzutat = new ZutatClass(zutatInput.getEditText().getText().toString(),anzahlintgetEditText().g etText().toString()
,einheitInput);
zutatenliste.add((String) newzutat.zutat_sting);
zutatenadapter.notifyDataSetChanged();
}
});
zutatInput.toString() --> zutatInput.getEditText().getText()
anzahlint.toString() --> anzahlint.getEditText().getText().toString()

How do I keep data in my Deque in Android Studio on Buttonclick?

I am trying to save data to a Deque on buttonclick and display the data in a tablelayout. My issue is that every time I trigger the onclick, the Deque loses all previous data. I tried to instantiate the Deque outside the onCreate method and it did not work. I am using a Deque as a stack because I need to display the data LIFO. Any help on this would be very much appreciated. Here is what I've tried so far:
public class MainActivity extends AppCompatActivity {
private Button buttonAdd;
private EditText editText1;
private Deque<String> input;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText editText1 = (EditText)findViewById(R.id.edit_text_1);
final Deque<String> input = new ArrayDeque<String>();
buttonAdd = (Button) findViewById(R.id.button_add);
buttonAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
TableLayout table = (TableLayout) findViewById(R.id.tableLayout1);
String data = editText1.getText().toString();
input.addFirst(data);
Deque<String> inputData = input;
while (!inputData.isEmpty()) {
String s = inputData.removeFirst();
TableRow row = new TableRow(MainActivity.this);
TextView textViewData = new TextView(MainActivity.this);
textViewData.setText(s);
textViewData.setGravity(Gravity.CENTER);
row.addView(textViewData);
table.addView(row);
}
}
});
}
}
The problem is this line:
String s = inputData.removeFirst();
With this operation, you remove (delete) the next entry and since you do it in a loop:
while (!inputData.isEmpty()) {
it simply empties the queue.
What you want is to iterate over the queue without removing anything:
for (String element : inputData) {
textViewData.setText(s);
}

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

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]

Categories

Resources