Button is clickable but doesn't work [closed] - android

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
So I have this code but when I'm trying it on my phone doesn't do anything..
I tried the version on firebase website too but it doesn't work. I would really appreciate if you can help me guys!
I think that this is the problem
Can someone help me with it?
public class LoginActivity extends AppCompatActivity {
public Firebase mFirebase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Firebase.setAndroidContext(this);
mFirebase = new Firebase("https://kip.firebaseio.com");
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_login);
}
public void onClickLogin(View v){
final String email = ((EditText) findViewById(R.id.email)).getText().toString();
final String password =((EditText) findViewById(R.id.password)).getText().toString();
mFirebase.createUser(email, password, new Firebase.ResultHandler() {
#Override
public void onSuccess() {
mFirebase.authWithPassword(email, password, null);
System.out.println("Successfully created user account!");
}
#Override
public void onError(FirebaseError firebaseError) {
mFirebase.authWithPassword(email, password, null);
System.out.println("There was an error connecting!");
}
});
}
}
Here is my XML
<Button
android:layout_width="300dp"
android:layout_height="wrap_content"
android:background="#drawable/button_login"
android:text="#string/login"
android:textColor="#android:color/white"
android:textSize="16sp"
android:id="#+id/button"
android:layout_below="#+id/password"
android:layout_centerHorizontal="true"
android:layout_marginTop="75dp"
android:onClick="onClickLogin"
android:clickable="true" />

Try with:
public class LoginActivity extends AppCompatActivity {
public Firebase mFirebase;
Button button = (Button) findViewById(R.id.button);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Firebase.setAndroidContext(this);
mFirebase = new Firebase("https://kip.firebaseio.com");
requestWindowFeature(Window.FEATURE_NO_TITLE);
button.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
final String email = ((EditText) findViewById(R.id.email)).getText().toString();
final String password =((EditText) findViewById(R.id.password)).getText().toString();
mFirebase.createUser(email, password, new Firebase.ResultHandler() {
#Override
public void onSuccess() {
mFirebase.authWithPassword(email, password, null);
System.out.println("Successfully created user account!");
}
#Override
public void onError(FirebaseError firebaseError) {
mFirebase.authWithPassword(email, password, null);
System.out.println("There was an error connecting!");
}
});
}
});
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_login);
}
}

This is the final code and it works!!
protected EditText mEmail;
protected EditText mPassword;
protected Button mLogin;
protected Button mRegister;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Firebase.setAndroidContext(this);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_login);
mEmail = (EditText) findViewById(R.id.email);
mPassword = (EditText) findViewById(R.id.password);
mLogin = (Button) findViewById(R.id.Login);
mRegister = (Button) findViewById(R.id.Register);
mLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Firebase ref = new Firebase("https://kip.firebaseio.com");
String email = mEmail.getText().toString().trim();
String password = mPassword.getText().toString().trim();
ref.authWithPassword(email, password, new Firebase.AuthResultHandler() {
#Override
public void onAuthenticated(AuthData authData) {
System.out.println("User ID: " + authData.getUid() + ", Provider: " + authData.getProvider());
Intent activity = new Intent(LoginActivity.this, HomeActivity.class);
startActivity(activity);
}
#Override
public void onAuthenticationError(FirebaseError firebaseError) {
// there was an error
}
});
}
});
mRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Firebase ref = new Firebase("https://kip.firebaseio.com");
String email = mEmail.getText().toString().trim();
String password = mPassword.getText().toString().trim();
ref.createUser(email, password, new Firebase.ValueResultHandler<Map<String, Object>>() {
#Override
public void onSuccess(Map<String, Object> result) {
System.out.println("Successfully created user account with uid: " + result.get("uid"));
}
#Override
public void onError(FirebaseError firebaseError) {
// there was an error
}
});
}
});
}
}

Related

Firebase Phone number authentication error, Phone number not readable

When I enter a phone number into my EditText field and press login, the java code has to validate if the editText field is empty or not. So after entering my phone no., the if(!phonenumber.isempty()) is always false and the else statement is executed, that is "Please enter number" Toast
Here is my compelete code:
public class User_login extends AppCompatActivity {
private EditText editTextphone;
private Button otp_login;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_login);
otp_login = (Button) findViewById(R.id.otp_login);
editTextphone = (EditText) findViewById(R.id.editTextphone);
String phoneNumber = editTextphone.getText().toString().trim();
mAuth = FirebaseAuth.getInstance();
ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
otp_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(!phoneNumber.isEmpty()){
if(phoneNumber.length() == 10){
progressBar.setVisibility(View.VISIBLE);
otp_login.setVisibility(View.INVISIBLE);
PhoneAuthOptions options = PhoneAuthOptions.newBuilder(mAuth)
.setPhoneNumber("+91" + phoneNumber)
.setTimeout(60L, TimeUnit.SECONDS)
.setActivity(User_login.this)
.build();
PhoneAuthProvider.verifyPhoneNumber(options);
new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(#NonNull #org.jetbrains.annotations.NotNull PhoneAuthCredential phoneAuthCredential) {
progressBar.setVisibility(View.GONE);
otp_login.setVisibility(View.VISIBLE);
}
#Override
public void onVerificationFailed(#NonNull #org.jetbrains.annotations.NotNull FirebaseException e) {
progressBar.setVisibility(View.GONE);
otp_login.setVisibility(View.VISIBLE);
Toast.makeText(User_login.this,"Some error occured" + e.getMessage(), Toast.LENGTH_LONG).show();
}
#Override
public void onCodeSent(#NonNull #org.jetbrains.annotations.NotNull String s, #NonNull #org.jetbrains.annotations.NotNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
Intent intent = new Intent(getApplicationContext(),opt_verify.class);
intent.putExtra("phone", editTextphone.getText().toString());
intent.putExtra("mVerificationId", s);
startActivity(intent);
}
};
}else{
Toast.makeText(User_login.this,"Please enter complete number",Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(User_login.this,"Please enter mobile number",Toast.LENGTH_LONG).show();
}
}
});
}
#Override
protected void onStart() {
super.onStart();
if(mAuth.getCurrentUser() != null){
startActivity(new Intent(this, home_user.class));
}
}
}
You should get the EditText input in the onClick Listner, only then you could get the latest inputted value from the edittext.
ie,
String phoneNumber = editTextphone.getText().toString().trim();
should be called inside :
otp_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String phoneNumber = editTextphone.getText().toString().trim(); //like this
if(!phoneNumber.isEmpty()){
There is a problem in your logic. The reason is that you are getting text before clicking the button meanwhile when the onCreate method runs it gets the value form the EditText. But you need get the value when you click the button each time.
Try this code:
otp_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String phoneNumber = editTextphone.getText().toString().trim();
if (!phoneNumber.isEmpty()) {
if (phoneNumber.length() == 10) {
//you logic or code here
}
}
}
}

UID for same user is different in Firebase database and authentication

I need to retrieve the data that i have stored in the Firebase database. But it shows that the UIDs are different in authentication part and database part.
UPDATE : Now i am facing problems while trying to fetch data from the firebase. I want to display it in a ListView. When i go from the Login Activity(after successful login) to the General Activity (where i put the ListView), it does not show up and the Activity switches from General to the Login one. I am attaching the code segments at the bottom under "UPDATE CODE" .
Help would be highly appreciated. Thanks!
Here is the code for registration
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
setUpUIviews();
firebaseAuth = FirebaseAuth.getInstance();
db = FirebaseDatabase.getInstance().getReference().child("users");
Register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (validate()){
String user_email = REmail.getText().toString().trim();
String user_password = RPass.getText().toString().trim();
firebaseAuth.createUserWithEmailAndPassword(user_email,user_password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
updateData();
Toast.makeText(Registration.this,"Registration Successful! ",Toast.LENGTH_SHORT).show();
startActivity(new Intent(Registration.this,MainActivity.class));
}else {
Toast.makeText(Registration.this,"Registration Unsuccessful ",Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
And this is the update data part:
private void updateData(){
String uName = RName.getText().toString().trim();
String uEmail = REmail.getText().toString().trim();
String id = db.push().getKey();
ProfileUpdate profileUpdate = new ProfileUpdate(uName,uEmail);
db.child(id).setValue(profileUpdate);
Toast.makeText(this,"Added info",Toast.LENGTH_SHORT).show();
}
UPDATE CODE
Login Activity
public class LoginPage extends AppCompatActivity {
private TextView userRegistration;
private TextView Info;
private EditText LName;
private EditText LPass;
private Button LSignIn;
private int counter = 3;
private FirebaseAuth firebaseAuth;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loginpage);
userRegistration = (TextView)findViewById(R.id.tvRegister);
LName = (EditText)findViewById(R.id.btnName);
LPass = (EditText)findViewById(R.id.btnPass);
LSignIn = (Button) findViewById(R.id.btnSignIn);
Info = (TextView) findViewById(R.id.tvInfo);
Info.setText( " No of attempts remaining: 3 " );
firebaseAuth = FirebaseAuth.getInstance();
progressDialog = new ProgressDialog(this);
FirebaseUser user= null;
if(user!=null){
finish();
startActivity(new Intent(LoginPage.this,General.class));
}
user = firebaseAuth.getCurrentUser();
LSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validate(LName.getText().toString(),LPass.getText().toString());
}
});
userRegistration.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginPage.this,Registration.class));
}
});
}
private void validate(String username, String password){
progressDialog.setMessage("Processing your request.... ");
progressDialog.show();
firebaseAuth.signInWithEmailAndPassword(username,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
progressDialog.dismiss();
Toast.makeText(LoginPage.this,"Login successful!",Toast.LENGTH_SHORT).show();
startActivity(new Intent(LoginPage.this,General.class));
}else {
Info.setText("No of attempts remaining: " + String.valueOf(counter-1));
Toast.makeText(LoginPage.this,"Please enter corrent credentials",Toast.LENGTH_SHORT).show();
counter --;
progressDialog.dismiss();
if(counter<=0){
LSignIn.setEnabled(false);
}
}
}
});
}
}
General Activity
public class General extends AppCompatActivity {
private FirebaseAuth firebaseAuth;
private Button Logout;
ListView l1;
ArrayAdapter<String> adapter;
DatabaseReference databaseReference;
FirebaseUser user;
List<String> itemlist;
String uid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_general);
firebaseAuth = FirebaseAuth.getInstance();
Logout = (Button) findViewById(R.id.btnLogout);
l1 = (ListView)findViewById(R.id.listView);
user = FirebaseAuth.getInstance().getCurrentUser();
uid = user.getUid();
itemlist = new ArrayList<>();
databaseReference = FirebaseDatabase.getInstance().getReference();
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
itemlist.clear();;
String user_name = dataSnapshot.child(uid).child("usrName").getValue(String.class);
String user_email = dataSnapshot.child(uid).child("ursEmail").getValue(String.class);
itemlist.add(user_name);
itemlist.add(user_email);
adapter = new ArrayAdapter<>(General.this,android.R.layout.simple_list_item_1,itemlist);
l1.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
firebaseAuth.signOut();
finish();
startActivity(new Intent(General.this, MainActivity.class));
}
});
}
}
activity_general.xml file
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/myApp"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".General">
<Button
android:id="#+id/btnLogout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:text="LOGOUT"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.467"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/listView" />
<ListView
android:id="#+id/listView"
android:layout_width="368dp"
android:layout_height="270dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
The Design
enter image description here
This is the code of how you store the user data into the datbase:
String id = db.push().getKey();
ProfileUpdate profileUpdate = new ProfileUpdate(uName,uEmail);
db.child(id).setValue(profileUpdate);
In the first line you call push().getKey() to get a new unique ID from the database SDK. This ID is not related to the user profile.
If you want to store the users in the database under their UID, you will need to get the UID from the AuthResult just after you created the user. Something like:
String uid = task.getResult().getUser().getUid();
When you pass this uid to your updateData method, you then create the child node the database with:
db.child(uid).setValue(profileUpdate);

Failed to convert value of type java.util.HashMap to String and app crashes

public class MainActivity extends AppCompatActivity {
//points to the root node of the database
DatabaseReference mRootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference mConditionRef = mRootRef.child("condition");
TextView content;
Button sunny, foggy;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
content = (TextView) findViewById(R.id.condition);
sunny = (Button) findViewById(R.id.sunny);
foggy = (Button) findViewById(R.id.foggy);
}
#Override
protected void onStart() {
super.onStart();
mConditionRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String text = dataSnapshot.getValue(String.class);
content.setText(text);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
sunny.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mConditionRef.setValue("Sunny");
mRootRef.child("condition").push().setValue("Abhijeet Jain2");
}
});
foggy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mConditionRef.setValue("Foggy");
}
});
}
}
The string gets added in the realtime database with a automatic made id but the app crashes as soon as I press the button "sunny".
What could be the reason and the solution?

How to update data in Firebase?

I am trying to update the quantity of a product in the database.Whenever I Add or Deduct the quantity, the change only reflects on my app but not updated in the Firebase! Any Help Will be greatly appreciated!
Here is a picture of the app:
Picture of database:
Here is my Code:
public class Edit extends AppCompatActivity {
String myKey = null;
private Button removebutton, plus, minus;
private int counterValue;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit);
removebutton = (Button) findViewById(R.id.item_detail_delete);
plus = (Button) findViewById(R.id.item_quantity_add);
minus = (Button) findViewById(R.id.item_quantity_remove);
final DatabaseReference database;
myKey = getIntent().getExtras().getString("value");
database = FirebaseDatabase.getInstance().getReference().child("All Barcodes");
database.child(myKey).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
TextView Barcode=(TextView) findViewById(R.id.Barcode);
TextView Pname=(TextView) findViewById(R.id.Pname);
TextView EntryDate=(TextView) findViewById(R.id.EntryDate);
TextView ExpiryDate=(TextView) findViewById(R.id.ExpiryDate);
final TextView Quantity=(TextView) findViewById(R.id.Quantity);
String barcode = (String) dataSnapshot.child("barcode").getValue();
String pname = (String) dataSnapshot.child("pname").getValue();
String date = (String) dataSnapshot.child("date").getValue();
String expiration = (String) dataSnapshot.child("expiration").getValue();
String quantity = (String) dataSnapshot.child("quantity").getValue();
Barcode.setText(barcode);
Pname.setText(pname);
EntryDate.setText(date);
ExpiryDate.setText(expiration);
Quantity.setText(quantity);
counterValue = Integer.valueOf(quantity);
plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counterValue ++;
Quantity.setText(String.valueOf(counterValue));
}
});
minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counterValue --;
Quantity.setText(String.valueOf(counterValue));
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getMessage());
}
});
removebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
database.child(myKey).removeValue();
Intent intent = new Intent(Edit.this,Inventory.class);
startActivity(intent);
}
});
}
You should update the related field in the database yourself:
plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counterValue++;
Quantity.setText(String.valueOf(counterValue));
database.child(myKey).child("quantity").setValue(String.valueOf(counterValue));
}
});
minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counterValue--;
Quantity.setText(String.valueOf(counterValue));
database.child(myKey).child("quantity").setValue(String.valueOf(counterValue));
}
});
The easiest way is to set keep sync to true like that:
DatabaseReference scoresRef = FirebaseDatabase.getInstance().getReference("scores");
scoresRef.keepSynced(true);
This is from the firebase documentation
https://firebase.google.com/docs/database/android/offline-capabilities

How String object is not receiving data from the editText? - Android

I have a problem with this, the editText in the log is sending data but the String is null and the object is null
this is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_group_chat);
mSendMessage = (ImageButton) findViewById(R.id.imageButtongrupalSend);
mGetText = (EditText) findViewById(R.id.textoDeEdicionChat);
mChat = new GroupalChat();
mPost = (Post) getIntent().getParcelableExtra("grupal");
final String lel = mGetText.getText().toString();
mChat.setMsj(lel);
mChat.setTiempoMensaje(System.currentTimeMillis());
mSendMessage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseUtils.getGrupalChatRef(mPost.getId()).push().setValue(mChat).addOnSuccessListener(GroupChatActivity.this, new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d("lol", lel);
Log.d("jeje", mChat.getMsj());
}
});
}
});
}
the log is not receiving anything
and the string is not receiving anything
Move this final String lel = mGetText.getText().toString(); inside the click listener and it will work.
mSendMessage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String lel = mGetText.getText().toString();
mChat = new GroupalChat();
mChat.setMsj(lel);
mChat.setTiempoMensaje(System.currentTimeMillis());
Log.d("lol", lel);
Log.d("jeje", mChat.getMsj());
FirebaseUtils.getGrupalChatRef(mPost.getId()).push().setValue(mChat).addOnSuccessListener(GroupChatActivity.this, new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d("lol", "Success");
}
});
}
});
Your version doesn't work because lel has already been bound to some value before the click listener has even been created.

Categories

Resources