I am working on recommendation application I using firebase to store information about user.I have used checkboxes for health status information.
I want to save all the checkbox values I selected.but in my code if I check more then one checkbox it always save the last checkbox.
This is my code How can I fix it to store all checked values?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
Toolbar toolbar =findViewById(R.id.toolbarotherpages);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
databaseUser = FirebaseDatabase.getInstance("https://bonappetit-808c5.firebaseio.com").getReference("users");
users = new ArrayList<>();
addusername= findViewById(R.id.editTextname);
addphone=findViewById(R.id.editTextphone2);
mFirstCheckBox=findViewById(R.id.cbox1);
mSecondCheckBox=findViewById(R.id.cbox2);
mThirdCheckBox=findViewById(R.id.cbox3);
addhealthstatus=findViewById(R.id.editTexthealthstatus);
btnsignup =findViewById(R.id.buttonsignup2);
btnsignup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Signup dosignup = new Signup(); // this is the Asynctask
dosignup.execute("");
}
});
}
protected void onStart() {
super.onStart();
//attaching value event listener
databaseUser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//clearing the previous artist list
users.clear();
//iterating through all the nodes
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
//getting artist
users user = postSnapshot.getValue(users.class);
//adding artist to the list
users.add(user);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public class Signup extends AsyncTask<String, String, String> {
String z = "";
Boolean isSuccess = false;
String username = addusername.getText().toString();
String phone = addphone.getText().toString();
String healthstatus = addhealthstatus.getText().toString();
#Override
protected String doInBackground(String... params) {
if (username.trim().equals("") || phone.trim().equals("")) {
z += "Please fill in all fields";
} else {
int count = 0;
for (users user2 : users) {
if (user2.getPhonenumber().equals(phone)) {
count = 1;
}
}
if (count == 0) {
try {
if(mFirstCheckBox.isChecked()) {
users user = new users(username, phone,"Diabetes");
databaseUser.child(phone).setValue(user);
addusername.setText("");
addphone.setText("");
addhealthstatus.setText("");
}
if(mSecondCheckBox.isChecked()) {
users user = new users(username, phone, "pressure");
databaseUser.child(phone).setValue(user);
addusername.setText("");
addphone.setText("");
addhealthstatus.setText("");
}
if(mThirdCheckBox.isChecked()) {
users user = new users(username, phone,
healthstatus);
databaseUser.child(phone).setValue(user);
addusername.setText("");
addphone.setText("");
addhealthstatus.setText("");
}
z = "Account created";
isSuccess = true;
}
catch (Exception ex) {
z = "Mobile number was used";
isSuccess = false;
}
}
}
return z;
}
}
To get the selected checked values you can use Switch case following code
public void onCheckboxClicked(View view) {
boolean checked = ((CheckBox) view).isChecked();
switch(view.getId()) {
case R.id.checkBox1:
....
break;
case R.id.checkBox2:
......
break;
case R.id.checkBox3:
......
break;`
Related
So I'm making an app in android studio, its like a fintech app. In one activity/page(SendMoney.java), you put in a number amount and tap the "Send Money" button, from here it goes to the page where you choose who you're sending this money to(SendReceiver.java). You select your desired recepient and tap on a second "Send Money" button, this then takes you to a success page that lists the amount sent and the username of the recepient(SendReceiverSuccessPage).
On the SendMoney page I need to get the amount inputted and pass that data to the SendReceiverSuccessPage, I've done this by using Intent and I've added this code to when the Send Money button is clicked, but in doing this what happens is that it for some reason creates multiple instances of the SendReceiver page it navigates to.
So on the SendReceiver page when I'm done and I hit the second "Send Money" button it just opens a new instance of SendReceiver whiles the SendReceiverSuccessPage is stuck in the background for some reason.
I need it to be one single smooth navigation flow where it goes from SendMoney to SendReceiver to SendReceiverSuccessPage without SendReceiver popping up multiple times and stacking ontop of the success page, all whiles being able to actively pass and retrieve the "AmountSent" data.
SendMoney.java
public class SendMoney extends AppCompatActivity {
FirebaseUser firebaseUser;
FirebaseAuth firebaseAuth;
FirebaseDatabase database;
Context context;
Double userAmountDouble;
MaterialButton sendMoneyButton;
ImageView backspace, back;
TextView amount, currentBalanceText, currency, one, two, three, four, five, six, seven, eight, nine, zero, dot;
#SuppressLint("SetTextI18n")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_money);
this.context = getApplicationContext();
// Instance of FirebaseAuth and Database
firebaseAuth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance();
firebaseUser = firebaseAuth.getCurrentUser();
// Hooks
back = findViewById(R.id.back);
amount = findViewById(R.id.amount);
currency = findViewById(R.id.currency);
currentBalanceText = findViewById(R.id.current_balance);
one = findViewById(R.id.one);
two = findViewById(R.id.two);
three = findViewById(R.id.three);
four = findViewById(R.id.four);
five = findViewById(R.id.five);
six = findViewById(R.id.six);
seven = findViewById(R.id.seven);
eight = findViewById(R.id.eight);
nine = findViewById(R.id.nine);
zero = findViewById(R.id.zero);
dot = findViewById(R.id.dot);
backspace = findViewById(R.id.backspace);
sendMoneyButton = findViewById(R.id.send_money_button);
sendMoneyButton.setText("Send GH₵0");
// Display send amount on button, in realtime
amount.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//sendMoneyButton.setText("Send GH₵0");
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
// This method is called whenever the text in the EditText changes
String userInputAmount = amount.getText().toString();
sendMoneyButton.setText("Send GH₵" + userInputAmount);
}
#Override
public void afterTextChanged(Editable editable) {
//
}
});
// Connect to the database
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Users");
assert firebaseUser != null;
// Get and show available balance
databaseReference.child(firebaseUser.getUid()).child("userMainBalance").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String currentBalance = snapshot.getValue(String.class);
assert currentBalance != null;
currentBalanceText.setText("GH₵"+ currentBalance + " AVAILABLE");
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
// Print an error message
System.out.println("Error retrieving user main balance: " + error.getMessage());
}
});
// Send Money Button
sendMoneyButton.setOnClickListener(v -> {
String userInputAmount = amount.getText().toString();
if (userInputAmount.equals("") || userInputAmount.equals("0")) {
Toast.makeText(getApplicationContext(),"Please enter an amount",Toast.LENGTH_SHORT).show();
} else {
userAmountDouble = Double.parseDouble(userInputAmount);
databaseReference.child(firebaseUser.getUid()).child("userMainBalance").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String currentBalance = snapshot.getValue(String.class);
assert currentBalance != null;
double currentBalanceDouble = Double.parseDouble(currentBalance);
if (userAmountDouble > currentBalanceDouble) {
Toast.makeText(getApplicationContext(),"Insufficient Balance",Toast.LENGTH_SHORT).show();
} else {
// Create an Intent and include the value of userInputAmount
Intent sendReceiverIntent = new Intent(getApplicationContext(), SendReceiver.class);
sendReceiverIntent.putExtra("USER_INPUT_AMOUNT", amount.getText().toString());
sendReceiverIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Start the SendReceiver activity
finish();
startActivity(sendReceiverIntent);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
// Print an error message
System.out.println("Error retrieving user main balance: " + error.getMessage());
}
});
}
});
// Click Listeners
back.setOnClickListener(v -> finish());
zero.setOnClickListener(v -> {
if (amount.getText().toString().equals("0")) {
amount.setText("0");
} else if (amount.getText().toString().length() == 7) {
amount.setText(amount.getText().toString());
} else {
amount.setText(amount.getText().toString() + "0");
}
});
one.setOnClickListener(v -> {
if (amount.getText().toString().equals("0")) {
amount.setText("1");
} else if (amount.getText().toString().length() == 7) {
amount.setText(amount.getText().toString());
} else {
amount.setText(amount.getText().toString() + "1");
}
});
two.setOnClickListener(v -> {
if (amount.getText().toString().equals("0")) {
amount.setText("2");
} else if (amount.getText().toString().length() == 7) {
amount.setText(amount.getText().toString());
} else {
amount.setText(amount.getText().toString() + "2");
}
});
three.setOnClickListener(v -> {
if (amount.getText().toString().equals("0")) {
amount.setText("3");
} else if (amount.getText().toString().length() == 7) {
amount.setText(amount.getText().toString());
} else {
amount.setText(amount.getText().toString() + "3");
}
});
four.setOnClickListener(v -> {
if (amount.getText().toString().equals("0")) {
amount.setText("4");
} else if (amount.getText().toString().length() == 7) {
amount.setText(amount.getText().toString());
} else {
amount.setText(amount.getText().toString() + "4");
}
});
five.setOnClickListener(v -> {
if (amount.getText().toString().equals("0")) {
amount.setText("5");
} else if (amount.getText().toString().length() == 7) {
amount.setText(amount.getText().toString());
} else {
amount.setText(amount.getText().toString() + "5");
}
});
six.setOnClickListener(v -> {
if (amount.getText().toString().equals("0")) {
amount.setText("6");
} else if (amount.getText().toString().length() == 7) {
amount.setText(amount.getText().toString());
} else {
amount.setText(amount.getText().toString() + "6");
}
});
seven.setOnClickListener(v -> {
if (amount.getText().toString().equals("0")) {
amount.setText("7");
} else if (amount.getText().toString().length() == 7) {
amount.setText(amount.getText().toString());
} else {
amount.setText(amount.getText().toString() + "7");
}
});
eight.setOnClickListener(v -> {
if (amount.getText().toString().equals("0")) {
amount.setText("8");
} else if (amount.getText().toString().length() == 7) {
amount.setText(amount.getText().toString());
} else {
amount.setText(amount.getText().toString() + "8");
}
});
nine.setOnClickListener(v -> {
if (amount.getText().toString().equals("0")) {
amount.setText("9");
} else if (amount.getText().toString().length() == 7) {
amount.setText(amount.getText().toString());
} else {
amount.setText(amount.getText().toString() + "9");
}
});
dot.setOnClickListener(v -> {
if (amount.getText().toString().equals("0")) {
amount.setText(".");
} else if (amount.getText().toString().length() == 7) {
amount.setText(amount.getText().toString());
} else {
amount.setText(amount.getText().toString() + ".");
}
});
backspace.setOnClickListener(v -> {
if (amount.getText().toString().equals("") | amount.getText().toString().equals("0")) {
amount.setText("0");
} else {
amount.setText(amount.getText().toString().substring(0, amount.getText().length() - 1));
}
});
}
}
SendReceiver.java
public class SendReceiver extends AppCompatActivity{
FirebaseUser firebaseUser;
FirebaseAuth firebaseAuth;
FirebaseDatabase database;
Context context;
ArrayList<SearchedUsersModel> searchedUsersModel;
RecyclerView searchedUsersRecycler;
SearchView svSearch;
MaterialButton finalSendBtn;
#SuppressLint("SetTextI18n")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sendreceiver);
// Retrieve the value of userInputAmount from the Intent
Intent intent = getIntent();
String userInputAmount = intent.getStringExtra("USER_INPUT_AMOUNT");
this.context = getApplicationContext();
// Instance of FirebaseAuth and Database
firebaseAuth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance();
firebaseUser = firebaseAuth.getCurrentUser();
// Hooks
searchedUsersRecycler = findViewById(R.id.recyclerUsers);
svSearch = findViewById(R.id.svSearch);
finalSendBtn = findViewById(R.id.final_send_button);
// Set the hint for the search bar
svSearch.setQueryHint("Enter name or email of user");
// On click listener for when you hit the Send button
finalSendBtn.setOnClickListener(v -> {
DatabaseReference databaseReference = database.getReference("Users");
assert firebaseUser != null;
databaseReference.child(firebaseUser.getUid()).child("transactions").child("sendTransactions").child(Objects.requireNonNull(databaseReference.push().getKey())).child("amount").setValue(userInputAmount);
// Get a reference to the "transactions" collection
DatabaseReference transactionsRef = database.getReference("Transactions");
// Get a reference to the "sendTransactions" sub-collection
DatabaseReference sendTransactionsRef = transactionsRef.child("sendTransactions");
// Generate a unique ID for the new transaction
String transactionUID = sendTransactionsRef.push().getKey();
// Add the new transaction to the "sendTransactions" sub-collection
assert transactionUID != null;
sendTransactionsRef.child(transactionUID).child("amount").setValue(userInputAmount);
// This deducts the same amount from the current users main balance
databaseReference.child(firebaseUser.getUid()).child("userMainBalance").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String currentBalance = snapshot.getValue(String.class);
DecimalFormat df = new DecimalFormat("0.00");
assert currentBalance != null;
// The current balance minus the amount withdrawn
double amountToSubtract = Double.parseDouble(currentBalance) - Double.parseDouble(userInputAmount);
String newBalance = Double.toString(Double.parseDouble(df.format(amountToSubtract)));
// Write the new balance to the database
databaseReference.child(firebaseUser.getUid()).child("userMainBalance").setValue(newBalance).addOnCompleteListener(task -> {
if (task.isSuccessful()) {
System.out.println("Error updating user main balance: " + task.getException());
} else {
// Print an error message
System.out.println("Error updating user main balance: " + task.getException());
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
// Print an error message
System.out.println("Error retrieving user main balance: " + error.getMessage());
}
});
finish();
startActivity(new Intent(getApplicationContext(), SendReceiverSuccessPage.class));
});
// Connect to the database
if (svSearch != null) {
svSearch.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
svSearch.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
if (!newText.isEmpty()) {
// Connect to the database
String currentUserId = Objects.requireNonNull(firebaseAuth.getCurrentUser()).getEmail();
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Users");
assert firebaseUser != null;
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(snapshot.exists()){
searchedUsersModel = new ArrayList<>();
for (DataSnapshot ds : snapshot.getChildren()) {
// Removes current user from list
SearchedUsersModel user = ds.getValue(SearchedUsersModel.class);
assert user != null;
if (!user.getMail().equals(currentUserId)) { // check if user's ID does not match current user's ID
searchedUsersModel.add(user); // add this user to the list of searched users
}
}
//Filter through the users based on Name or Email
ArrayList<SearchedUsersModel> myList = new ArrayList<>();
for(SearchedUsersModel object : searchedUsersModel) {
if(object.getMail().toLowerCase().contains(newText.toLowerCase())) {
myList.add(object);
}
else if(object.getName().toLowerCase().contains(newText.toLowerCase())) {
myList.add(object);
}
}
SearchedUsersAdapter searchedUsersAdapter = new SearchedUsersAdapter(myList, finalSendBtn, svSearch);
searchedUsersRecycler.setAdapter(searchedUsersAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
} else {
// Clear the data from the RecyclerView
searchedUsersModel = new ArrayList<>();
SearchedUsersAdapter searchedUsersAdapterClass = new SearchedUsersAdapter(searchedUsersModel, finalSendBtn, svSearch);
searchedUsersRecycler.setAdapter(searchedUsersAdapterClass);
//Set button to disabled
finalSendBtn.setEnabled(false);
}
return false;
}
});
return true;
}
});
}
}
}
SendReceiverSuccessPage
public class SendReceiverSuccessPage extends AppCompatActivity {
MaterialButton greatNextButton;
TextView sendSuccessText;
public static String usersName;
FirebaseUser firebaseUser;
FirebaseAuth firebaseAuth;
FirebaseDatabase database;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sendreceiver_success_page);
// Instance of FirebaseAuth and Database
firebaseAuth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance();
firebaseUser = firebaseAuth.getCurrentUser();
greatNextButton = findViewById(R.id.great_next_button);
sendSuccessText = findViewById(R.id.send_success);
//Get sent amount from database
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Users");
assert firebaseUser != null;
DatabaseReference transactionsRef = databaseReference.child(firebaseUser.getUid()).child("transactions");
DatabaseReference sendTransactionsRef = transactionsRef.child("sendTransactions");
//
sendTransactionsRef.orderByKey().limitToLast(1).addListenerForSingleValueEvent(new ValueEventListener() {
#SuppressLint("SetTextI18n")
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot transactionSnapshot : dataSnapshot.getChildren()) {
String lastTransactionKey = transactionSnapshot.getKey();
assert lastTransactionKey != null;
sendTransactionsRef.child(lastTransactionKey).child("amount").addValueEventListener(new ValueEventListener() {
#SuppressLint("SetTextI18n")
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String sentAmount = snapshot.getValue(String.class);
sendSuccessText.setText("GH₵" + sentAmount + " has been sent to " + usersName);
//TODO This can also be where receiveTransactions document is created in the users database
// This sends the money to the chosen user by their name
databaseReference.orderByChild("name").equalTo(usersName).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot userSnapshot : snapshot.getChildren()) {
// Get the main balance of the chosen user
String mainBalance = userSnapshot.child("userMainBalance").getValue(String.class);
DecimalFormat df = new DecimalFormat("0.00");
// Convert the main balance and amount sent to doubles
assert mainBalance != null;
double mainBalanceDouble = Double.parseDouble(mainBalance);
assert sentAmount != null;
double amountSentDouble = Double.parseDouble(sentAmount);
// Add the amount sent to the main balance
double updatedMainBalance = mainBalanceDouble + amountSentDouble;
// Convert the updated main balance back to a string
String updatedMainBalanceString = Double.toString(Double.parseDouble(df.format(updatedMainBalance)));
// Update the main balance in the database for the chosen user
userSnapshot.getRef().child("userMainBalance").setValue(updatedMainBalanceString);
userSnapshot.getRef().child("transactions").child("receivedTransactions").child(Objects.requireNonNull(databaseReference.push().getKey())).child("amount").setValue(sentAmount);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
// Print an error message
System.out.println("Error retrieving user main balance: " + error.getMessage());
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
// Handle error
}
});
greatNextButton.setOnClickListener(v -> {
startActivity(new Intent(getApplicationContext(), MainDashboard.class));
});
}
}
There are also some Adapter classes I can add if needed.
I've been trying to figure it out with ChatGPT and have literally tried out everything.
Through testing I found out that anytime I take the
Intent sendReceiverIntent = new Intent(getApplicationContext(), SendReceiver.class);
sendReceiverIntent.putExtra("USER_INPUT_AMOUNT", amount.getText().toString());
sendReceiverIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
lines out of the sendMoney button it ended up not creating multiple instances and working exactly like how I need it to. The only problem is that the amount sent that I need to pass to the success page isn't recoreded or passed. So ideally, if I could find a way or alternative to getting this data to the desired page without putting it into the button OnClick or having it create multiple instances of the activity.
I have added all the strings, private booleans in the Signup.java and properly added all the firebase dependencies. Plus, Added the codes in Login.java to retrieve all the firebase data after successful signup. However, there is no error showing in the codes but still, the sign-in screen functionalites aren't working. When I click on "Signin" button the apps showing me "This app has stopped"
Here's the code that I have written on login.java
public class Login extends AppCompatActivity {
Button callSignUp, reg_btn;
TextInputLayout username, password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_login);
callSignUp = findViewById(R.id.signupscreen);
callSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Login.this, SignUp.class);
startActivity(intent);
}
});
//All elements Hooks
username = findViewById(R.id.reg_username);
password = findViewById(R.id.reg_password);
reg_btn = findViewById(R.id.reg_btn);
}
private Boolean validateUsername() {
String val = username.getEditText().getText().toString();
if (val.isEmpty()) {
username.setError("Please enter your username");
return false;
} else {
username.setError(null);
username.setErrorEnabled(false);
return true;
}
}
private Boolean validatePassword() {
String val = password.getEditText().getText().toString();
if (val.isEmpty()) {
password.setError("Please enter your password");
return false;
} else {
password.setError(null);
password.setErrorEnabled(false);
return true;
}
}
public void loginUser(View view) {
//validate user login
if (!validateUsername() | !validatePassword()) {
return;
} else {
isUser();
}
}
private void isUser() {
final String userEnteredUsername = username.getEditText().getText().toString().trim();
final String userEnteredPassword = password.getEditText().getText().toString().trim();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("users");
Query checkUser = reference.orderByChild("username").equalTo(userEnteredUsername);
checkUser.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
username.setError(null);
username.setErrorEnabled(false);
String passwordFromDB = dataSnapshot.child(userEnteredUsername).child("password").getValue(String.class);
if (passwordFromDB.equals(userEnteredPassword)) {
String nameFromDB = dataSnapshot.child(userEnteredUsername).child("name").getValue(String.class);
String emailFromDB = dataSnapshot.child(userEnteredUsername).child("email").getValue(String.class);
String usernameFromDB = dataSnapshot.child(userEnteredUsername).child("username").getValue(String.class);
String phoneNoFromDB = dataSnapshot.child(userEnteredUsername).child("phoneNo").getValue(String.class);
Intent intent = new Intent(getApplicationContext(), UserProfile.class);
intent.putExtra("name", nameFromDB);
intent.putExtra("username", usernameFromDB);
intent.putExtra("phoneNo", phoneNoFromDB);
intent.putExtra("password", passwordFromDB);
startActivity(intent);
} else {
password.setError("Wrong Password");
}
} else {
username.setError("Opps! No Such User Exist!");
username.requestFocus();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
//Call SignUp Screen
public void callSignUpScreen(View view) {
//To call next activity
Intent intent = new Intent(Login.this, SignUp.class);
}
}
Can anyone please tell me why the issue is happening?
Thanks
The app is about making a simple survey with checkboxes. The checkbox values come from REST Api as list like ["option1", "option2"...]
I will post selected checkboxes as also a list. All set and working except for removing unselected items. How can I get and remove 'unselected' data from list?
(User may make changes) I tried with List and HashMap, couldn't make it. Thanks in advance!
public class MainActivity extends AppCompatActivity {
LinearLayout linear_checkbox;
List<String> answerList= new ArrayList<>();
List<String> checkedList = new ArrayList<>();
Map<String,String> map = new HashMap<>();
Button button_send;
int j;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//
linear_checkbox = (LinearLayout)findViewById(R.id.linear_checkbox);
button_send= (Button)findViewById(R.id.button_send);
//
answerList.add("Photography");
answerList.add("Music");
answerList.add("Skateboard");
listChoices(cevapList);
button_send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Toast.makeText(MainActivity.this, "LIST: "+"\n"+ checkedList.toString(), Toast.LENGTH_SHORT).show();
//Toast.makeText(MainActivity.this, ""+map.toString(), Toast.LENGTH_SHORT).show();
}
});
}
public void listChoices(List<String> textList){
textList = answerList;
for(j=0; j<textList.size(); j++){
final CheckBox cb = new CheckBox(getApplicationContext());
cb.setText(textList.get(j));
cb.setTextColor(Color.parseColor("#E7740D"));
linear_checkbox.addView(cb);
cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(b==true){
Toast.makeText(MainActivity.this, ""+cb.getText()+" selected", Toast.LENGTH_SHORT).show();
String key = String.valueOf(j);
//map.put(key,cb.getText().toString());
secilenlerList.add(cb.getText().toString());
}else{
Toast.makeText(MainActivity.this, ""+cb.getText()+" unselected", Toast.LENGTH_SHORT).show();
}
}
});
}
}
}
Update your code its working fine. You didn't make changes when user unselect any check box item.
public class MainActivity extends AppCompatActivity {
LinearLayout linear_checkbox;
List<String> answerList = new ArrayList<>();
List<String> checkedList = new ArrayList<>();
Map<String, String> map = new HashMap<>();
Button button_send;
int j;
private ArrayList<String> secilenlerList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//
linear_checkbox = (LinearLayout) findViewById(R.id.linear_checkbox);
button_send = (Button) findViewById(R.id.button_send);
//
answerList.add("Photography");
answerList.add("Music");
answerList.add("Skateboard");
listChoices(answerList);
button_send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "LIST: " + "\n" + secilenlerList.toString(), Toast.LENGTH_SHORT).show();
//Toast.makeText(MainActivity.this, ""+map.toString(), Toast.LENGTH_SHORT).show();
}
});
}
public void listChoices(List<String> textList) {
textList = answerList;
secilenlerList = new ArrayList<>();
for (j = 0; j < textList.size(); j++) {
final CheckBox cb = new CheckBox(getApplicationContext());
cb.setText(textList.get(j));
cb.setTextColor(Color.parseColor("#E7740D"));
linear_checkbox.addView(cb);
cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean ischecked) {
if (ischecked) {
Toast.makeText(MainActivity.this, "" + cb.getText() + " selected", Toast.LENGTH_SHORT).show();
String key = String.valueOf(j);
//map.put(key,cb.getText().toString());
if (!secilenlerList.contains(cb.getText().toString()))
secilenlerList.add(cb.getText().toString());
} else {
if (secilenlerList.contains(cb.getText().toString()))
secilenlerList.remove(cb.getText().toString());
Toast.makeText(MainActivity.this, "" + cb.getText() + " unselected", Toast.LENGTH_SHORT).show();
}
}
});
}
}
}
I've got input city form, where it has 2 element, EditText for city name and Spinner a that has been populate Province Data from Firebase database. I want to make nodes structure in Firebase like this:
database{
provinces{
provinceId_1{
provinceId_1 : value
provinceName_1 : value
}
provinceId_2{
provinceId_2 : value
provinceName_2 : value
}
}
cities{
provinceId_1{
cityId_1{
cityId_1 : value
cityName_1 : value
}
cityId_2{
cityId_2 : value
cityName_2 : value
}
}
provinceId_2{
cityId_3{
cityId_3 : value
cityName_3 : value
}
}
}
}
But i do not know how to acquire provinces id and store it to cities table in firebase database, here's my code :
public class AddCityActivity extends AppCompatActivity {
private EditText inputCity;
private Button btnAddCity, btnClearText;
private MaterialSpinner spinnerProvinces;
private DatabaseReference databaseCities, databaseProvinces;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_city);
inputCity = (EditText) findViewById(R.id.add_city_edit_text);
btnAddCity = (Button) findViewById(R.id.action_add_city_button);
btnClearText = (Button) findViewById(R.id.action_clear_text_button);
spinnerProvinces = (MaterialSpinner) findViewById(R.id.provinceSpinner);
databaseProvinces = FirebaseDatabase.getInstance().getReference().child("provinces");
databaseProvinces.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final List<String> provinces = new ArrayList<String>();
for (DataSnapshot provinceSnapshot : dataSnapshot.getChildren()) {
String provinceName = provinceSnapshot.child("provinceName").getValue(String.class);
provinces.add(provinceName);
}
MaterialSpinner provincesSpinner = (MaterialSpinner) findViewById(R.id.provinceSpinner);
ArrayAdapter<String> provincesAdapter = new ArrayAdapter<String>(AddCityActivity.this, android.R.layout.simple_spinner_item, provinces); provincesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
provincesSpinner.setAdapter(provincesAdapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
btnClearText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
inputCity.setText("");
}
});
btnAddCity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addCity();
}
});
}
private void addCity() {
String name = inputCity.getText().toString().trim();
databaseCities = FirebaseDatabase.getInstance().getReference("cities");
if (!TextUtils.isEmpty(name)) {
String id = databaseCities.push().getKey();
City city = new City(id, name);
databaseCities.child(id).setValue(city);
Toast.makeText(this, "City Added", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Enter City Name", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onBackPressed() {
startActivity(new Intent(AddCityActivity.this, LandingActivity.class));
finish();
}
}
I'm currently making a quiz app, and I want to add a feature where users can register, and then use SQL to store this. I have followed this YouTube tutorial:
https://www.youtube.com/watch?v=NT1qxmqH1eM
However, when I have register a new user and try to login with this, it says "invalid password". So the data isn't being stored...
Home.java
Looks like this:
The code for Home.java is:
public class Home extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Button btnSignIn = (Button) findViewById(R.id.buttonSignIN);
Button btnSignUp = (Button) findViewById(R.id.buttonSignUP);
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intentSignIN = new Intent(Home.this, LoginActivity.class);
startActivity(intentSignIN);
}
});
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intentSignUP = new Intent(Home.this, Register.class);
startActivity(intentSignUP);
}
});
}
}
Pressing the SIGN UP button takes you to Register.java which looks like this:
The code for Register.java is:
public class Register extends Activity {
LoginDataBaseAdapter helper = new LoginDataBaseAdapter(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
}
public void onRegisterClick(View v)
{
if (v.getId() == R.id.register_complete) //changed from xml in activity_home which has id buttonSignUP
{
EditText email = (EditText)findViewById(R.id.editEmail);
EditText pass1 = (EditText)findViewById(R.id.editTextPassword);
EditText pass2 = (EditText)findViewById(R.id.editTextConfirmPassword);
String emailstr = email.getText().toString();
String pass1str = pass1.getText().toString();
String pass2str = pass2.getText().toString();
if (!pass1str.equals(pass2str))
{
//popup message
Toast pass = Toast.makeText(Register.this, "Passwords don't match!", Toast.LENGTH_SHORT);
pass.show();
}
else
{
//insert input in database
UserInfo u = new UserInfo();
u.setEmail(emailstr);
u.setPass(pass1str);
helper.insertUserInfo(u);
}
Intent registerIntent = new Intent(Register.this, Home.class);
startActivity(registerIntent);
}
}
}
I'm able to enter the details, click "complete registration" which then takes me back to Home.java. However, when I try to log in with a newly registered user, it's says that password is unknown. I guess it means the register data isn't then properly stored, but I can't figure out where I've gone wrong.
LoginActivity.java
I have used the template provided by Android Studio so most of this code isn't written by me. However, I have commented the code that I have added to it in order to create this database:
public class LoginActivity extends AppCompatActivity implements LoaderCallbacks<Cursor> {
LoginDataBaseAdapter helper = new LoginDataBaseAdapter(this); //FOR THE REGISTER DATABASE
/**
* Id to identity READ_CONTACTS permission request.
*/
private static final int REQUEST_READ_CONTACTS = 0;
/**
* A dummy authentication store containing known user names and passwords.
* TODO: remove after connecting to a real authentication system.
*/
private static final String[] DUMMY_CREDENTIALS = new String[]{
"foo#example.com:hello", "bar#example.com:world"
};
private User myUser;
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
private UserLoginTask mAuthTask = null;
// UI references.
private AutoCompleteTextView mEmailView;
private EditText mPasswordView;
private View mProgressView;
private View mLoginFormView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// Set up the login form.
mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
populateAutoComplete();
mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
if (id == R.id.login || id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});
Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
mEmailSignInButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
attemptLogin();
}
});
mLoginFormView = findViewById(R.id.login_form);
mProgressView = findViewById(R.id.login_progress);
}
public void onRegisterClick(View v){ //FOR THE REGISTER DATABASE (this method)
EditText a = (EditText)findViewById(R.id.email);
String str = a.getText().toString();
EditText b = (EditText)findViewById(R.id.password);
String pass = b.getText().toString();
String password = helper.searchPass(str);
if (pass.equals(password)){
Intent i = new Intent(LoginActivity.this, Play.class);
i.putExtra("Username", str);
startActivity(i);
}
else {
Toast temp = Toast.makeText(LoginActivity.this, "Username and password don't match!", Toast.LENGTH_SHORT);
temp.show();
}
}
private void populateAutoComplete() {
if (!mayRequestContacts()) {
return;
}
getLoaderManager().initLoader(0, null, this);
}
private boolean mayRequestContacts() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return true;
}
if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
return true;
}
if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
Snackbar.make(mEmailView, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE)
.setAction(android.R.string.ok, new View.OnClickListener() {
#Override
#TargetApi(Build.VERSION_CODES.M)
public void onClick(View v) {
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
}
});
} else {
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
}
return false;
}
/**
* Callback received when a permissions request has been completed.
*/
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
if (requestCode == REQUEST_READ_CONTACTS) {
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
populateAutoComplete();
}
}
}
/**
* Attempts to sign in or register the account specified by the login form.
* If there are form errors (invalid email, missing fields, etc.), the
* errors are presented and no actual login attempt is made.
*/
private void attemptLogin() {
if (mAuthTask != null) {
return;
}
// Reset errors.
mEmailView.setError(null);
mPasswordView.setError(null);
// Store values at the time of the login attempt.
String email = mEmailView.getText().toString();
String password = mPasswordView.getText().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid password, if the user entered one.
if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
mPasswordView.setError(getString(R.string.error_invalid_password));
focusView = mPasswordView;
cancel = true;
}
// Check for a valid email address.
if (TextUtils.isEmpty(email)) {
mEmailView.setError(getString(R.string.error_field_required));
focusView = mEmailView;
cancel = true;
} else if (!isEmailValid(email)) {
mEmailView.setError(getString(R.string.error_invalid_email));
focusView = mEmailView;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
showProgress(true);
mAuthTask = new UserLoginTask(email, password);
mAuthTask.execute((Void) null);
}
}
private boolean isEmailValid(String email) {
//TODO: Replace this with your own logic
return email.contains("#");
}
private boolean isPasswordValid(String password) {
//TODO: Replace this with your own logic
return password.length() > 4;
}
/**
* Shows the progress UI and hides the login form.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
mLoginFormView.animate().setDuration(shortAnimTime).alpha(
show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
});
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mProgressView.animate().setDuration(shortAnimTime).alpha(
show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
} else {
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
return new CursorLoader(this,
// Retrieve data rows for the device user's 'profile' contact.
Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,
// Select only email addresses.
ContactsContract.Contacts.Data.MIMETYPE +
" = ?", new String[]{ContactsContract.CommonDataKinds.Email
.CONTENT_ITEM_TYPE},
// Show primary email addresses first. Note that there won't be
// a primary email address if the user hasn't specified one.
ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
}
#Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
List<String> emails = new ArrayList<>();
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
emails.add(cursor.getString(ProfileQuery.ADDRESS));
cursor.moveToNext();
}
addEmailsToAutoComplete(emails);
}
#Override
public void onLoaderReset(Loader<Cursor> cursorLoader) {
}
private void addEmailsToAutoComplete(List<String> emailAddressCollection) {
//Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
ArrayAdapter<String> adapter =
new ArrayAdapter<>(LoginActivity.this,
android.R.layout.simple_dropdown_item_1line, emailAddressCollection);
mEmailView.setAdapter(adapter);
}
private interface ProfileQuery {
String[] PROJECTION = {
ContactsContract.CommonDataKinds.Email.ADDRESS,
ContactsContract.CommonDataKinds.Email.IS_PRIMARY,
};
int ADDRESS = 0;
int IS_PRIMARY = 1;
}
/**
* Represents an asynchronous login/registration task used to authenticate
* the user.
*/
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
private final String mEmail;
private final String mPassword;
UserLoginTask(String email, String password) {
mEmail = email;
mPassword = password;
}
#Override
protected Boolean doInBackground(Void... params) {
DBTools dbTools=null;
// TODO: attempt authentication against a network service.
try {
// Simulate network access.
Thread.sleep(2000);
} catch (InterruptedException e) {
return false;
}
for (String credential : DUMMY_CREDENTIALS) {
String[] pieces = credential.split(":");
if (pieces[0].equals(mEmail)) {
// Account exists, return true if the password matches.
return pieces[1].equals(mPassword);
}
}
// TODO: register the new account here.
return false; //changed
}
#Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) { ///if successful login
finish();
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
LoginActivity.this.startActivity(intent);
} else {
mPasswordView.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}
#Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
}
LoginDataBaseAdapter.java
public class LoginDataBaseAdapter extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "userinfo.db";
private static final String TABLE_NAME = "userinfo";
private static final String COLUMN_EMAIL = "email";
private static final String COLUMN_PASS = "pass";
SQLiteDatabase db;
private static final String TABLE_CREATE = "create table userinfo (email text not null, pass text not null);";
public LoginDataBaseAdapter(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABLE_CREATE);
this.db = db;
}
public void insertUserInfo(UserInfo u) {
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_EMAIL, u.getEmail());
values.put(COLUMN_PASS, u.getPass());
db.insert(TABLE_NAME, null, values);
db.close();
}
public String searchPass(String email) {
db = this.getReadableDatabase();
String query = "select email, pass from " + TABLE_NAME;
Cursor cursor = db.rawQuery(query, null);
String a, b;
b = "not found";
if(cursor.moveToFirst()) {
do{
a = cursor.getString(0);
b = cursor.getString(1);
if(a.equals(email)) {
b = cursor.getString(1);
break;
}
}
while(cursor.moveToNext());
}
return b;
}
#Override
public void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion) {
String query = "DROP TABLE IF EXISTS "+TABLE_NAME;
db.execSQL(query);
this.onCreate(db);
}
}
UserInfo.java
public class UserInfo {
String email, pass;
public void setEmail(String email)
{
this.email = email;
}
public String getEmail()
{
return this.email;
}
public void setPass(String pass)
{
this.pass = pass;
}
public String getPass()
{
return this.pass;
}
}
I'm new to programming, and I'm doing this for a school project, so a detailed explanation would be helpful. Thanks!
I do not have a specfic answer for your issue but one thing that would help is to check the SQLite database for the username and password after inserting the values. By checking the the values on the database you can see if the values that were recorded for the username. One easy way of checking the database is by using stetho which enables chrome developer tools, among them the ability to see the database.
To add stetho to your app, just add compile 'com.facebook.stetho:stetho:1.4.2' to your dependencies in the app gradle file.
And once the app loads gchrome://inspect/#devices to show the devices and then select your app.
After that you can see the contents of the database