If statement, Android Studio with Firebase - android

So I am trying to send data back to my Firebase Database with only users that have signed up and logged in. I have written a code to send the data but i am trying to write an else if statement that a message in this case a Toast appears if they have not signed up. I am struggling to write a code for that.
private void sendScore() {
String userName = name.getText().toString();
String userScore = BenchScore.getText().toString();
if(!TextUtils.isEmpty(userName) && !TextUtils.isEmpty(userScore)) {
String id = databaseReference.push().getKey();
ScoreProfile scoreProfile = new ScoreProfile(id, userName, userScore);
databaseReference.child(FirebaseAuth.getInstance().getUid()).setValue(scoreProfile);
name.setText("");
BenchScore.setText("");
} else if(FirebaseAuth.getInstance().) {
Toast.makeText(Score.this, "You need to sign up in order to use this", Toast.LENGTH_SHORT).show();
}
}

If you want to check if an user is logged in you can use :
...
else if( FirebaseAuth.getInstance().getCurrentUser() == null )
{
// Call your toast here
}

Replace ur code with this one:
private void sendScore() {
String userName = name.getText().toString();
String userScore = BenchScore.getText().toString();
if(FirebaseAuth.getInstance().getUid() != null && !TextUtils.isEmpty(userName) && !TextUtils.isEmpty(userScore)){
String id = databaseReference.push().getKey();
ScoreProfile scoreProfile = new ScoreProfile(id, userName, userScore);
databaseReference.child(FirebaseAuth.getInstance().getUid()).setValue(scoreProfile);
name.setText("");
BenchScore.setText("");
} else if (FirebaseAuth.getInstance().getUid() == null) {
Toast.makeText(Score.this, "You need to sign up in order to use this", Toast.LENGTH_SHORT).show();
}
}
I've just included a check for whether getUid() is non null in the if statement and in else if, I've checked whether getUid() is null. This would serve your purpose, hopefully.

Related

i want "enter data" msg when ever i click on submit button without filling the details and decreasing id value whenever i delete 1 item

i have created a app with 3 edit text and and 3 buttons,
Edittext:
- id
- name
- date
Button:
submit.
check.
delete.
name to store name of user,
date to store date,
submit to store data in sqlit database,
check to retrive data,
delete to delete the specfied id in database,
id is auto incremented it is used when deleting.
my problem here is if i not enter anything in the edit text it takes null values
and display as shown in below pic instead of taking null i want to show message "PLEASE ENTER DATA"
and whenever i delete data next id value must decrease by 1 please help me.
Before entering the data to database use should check EditTexts are null or not in on click method and if null print toast messages like below
idEditText = (EditText) findViewById(R.id.editText_id);
nameEditText = (EditText) findViewById(R.id.editText_Name);
dateEditText = (EditText) findViewById(R.id.editText_Date);
String id = idEditText.getText().toString().trim();
String name = nameEditText.getText().toString().();
String date = dateEditText.getText().toString().();
if(id.length() == 0 || name.length() == 0 || date.length())
{
Toast.makeText(this, "Please fill all details",Toast.LENGTH_SHORT).show();
}
Try this
idEditText =(EditText) findViewById(R.id.editText_id);
nameEditText =(EditText)findViewById(R.id.editText_Name);
dateEditText =(EditText)findViewById(R.id.editText_Date);
private boolean checkEmptyFields() {
boolean check = false
String id = idEditText.getText().toString().trim();
String name = nameEditText.getText().toString().trim();
String date = dateEditText.getText().toString().trim();
if (id.isEmpty()) {
idEditText.setError("Invalid Input");
check = true;
} else {
dEditText.setError(null);
check = false;
}
if (name.isEmpty()) {
nameEditText.setError("Invalid Input");
check = true;
} else {
nameEditText.setError(null);
check = false;
}
if (date.isEmpty()) {
dateEditText.setError("Invalid Input");
check = true;
} else {
dateEditText.setError(null);
check = false;
}
return check;
}
if (!checkEmptyFields())
{
//Add Data to DB
}

Mandatory fields in android [duplicate]

This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 1 year ago.
Hello I am making an app where user can order some books. When he, or she, fill out the order with his firs second name etc and hits order button applications,using Intent, will switch to SMS and thus will purchase books via text message.But i wish to be able, if user accidently forget to fill up all fields, toast pop up with message "Please fill up XYZ field". I used if else, but when some field remain empty something else happened.I got android message that my app needs to be closed and and return me to the previous activity.In my LogCat nothing happened . No error message.
this is my code :
public void kreiranjeNarudzbine(View v) {
EditText editTextIme = (EditText) findViewById(R.id.ime);
String imeNarucioca = editTextIme.getText().toString();
EditText editTextPrezime = (EditText)findViewById(R.id.prezime);
String prezimeNarucioca = editTextPrezime.getText().toString();
EditText editTelefonNarucioca = (EditText)findViewById(R.id.telefon);
String telefonNarucioca = editTelefonNarucioca.getText().toString();
EditText editAdresaNarucioca = (EditText)findViewById(R.id.adresa);
String adresaNarucioca = editAdresaNarucioca.getText().toString();
EditText editGradNarucioca = (EditText)findViewById(R.id.grad);
String gradNarucioca = editGradNarucioca.getText().toString();
EditText editKolicina = (EditText)findViewById(R.id.kolicina);
String narucenaKolicina = editKolicina.getText().toString();
int kolicina = Integer.parseInt(narucenaKolicina);
int cenaNarudzbine = cena(kolicina);
String poruka = sumiranjeNarudzbine(imeNarucioca, prezimeNarucioca,telefonNarucioca,adresaNarucioca,gradNarucioca,cenaNarudzbine);
Intent smsIntent = new Intent(Intent.ACTION_VIEW);
smsIntent.setType("vnd.android-dir/mms-sms");
smsIntent.putExtra("address", "+381629647169");
smsIntent.putExtra("sms_body",poruka);
if(imeNarucioca.equals("")){
Toast.makeText(Narudzbina.this, "Unesite ime", Toast.LENGTH_LONG).show();
}
else if(prezimeNarucioca.equals("")){
Toast.makeText(Narudzbina.this,"Unesite Prezime", Toast.LENGTH_LONG).show();
}
else if(telefonNarucioca.equals("")){
Toast.makeText(Narudzbina.this,"Unesite kontakt telefon", Toast.LENGTH_LONG).show();
}
else if(adresaNarucioca.equals("")){
Toast.makeText(Narudzbina.this,"Unesite adresu",Toast.LENGTH_LONG).show();
}
else if(gradNarucioca.equals("")){
Toast.makeText(Narudzbina.this, "Navedite grad", Toast.LENGTH_LONG).show();
}
else if(narucenaKolicina.equals("")){
Toast.makeText(Narudzbina.this, "Navedite zeljenu kolicinu", Toast.LENGTH_LONG).show();
}
else{
startActivity(smsIntent);}
}
As already mentioned, you check to make sure it isn't null or empty.
if(imeNarucioca!=null && imeNarucioca.equals("")){
Toast.makeText(Narudzbina.this, "Unesite ime", Toast.LENGTH_LONG).show();
}
else if(prezimeNarucioca!=null && prezimeNarucioca.equals("")){
Toast.makeText(Narudzbina.this,"Unesite Prezime", Toast.LENGTH_LONG).show();
}
else if(telefonNarucioca!=null && telefonNarucioca.equals("")){
Toast.makeText(Narudzbina.this,"Unesite kontakt telefon", Toast.LENGTH_LONG).show();
}
else if(adresaNarucioca!=null && adresaNarucioca.equals("")){
Toast.makeText(Narudzbina.this,"Unesite adresu",Toast.LENGTH_LONG).show();
}
else if(gradNarucioca!=null && gradNarucioca.equals("")){
Toast.makeText(Narudzbina.this, "Navedite grad", Toast.LENGTH_LONG).show();
}
else if(narucenaKolicina!=null && narucenaKolicina.equals("")){
Toast.makeText(Narudzbina.this, "Navedite zeljenu kolicinu", Toast.LENGTH_LONG).show();
}
else{
startActivity(smsIntent);
}
This can be converted into a method to prevent as much text:
public boolean isETEmpty(EditText et){
return (et != null && (et.equals("") || et.equals(" ")));//the final piece checks if the edittext is empty or just contains a space. It is or between
//in order to ensure that one of those are true. Thus the parenthesis
}
(how the above works)
Now, for the required fields you can use HTML to format the text:
/*your view*/.setText(Html.fromHtml("Your title. <font color='red'>*</font>"));
The above code formats the code by adding a red star after the required fields. Later down you can do this:
/*your view*/.setText(Html.fromHtml("<font color='red'>*</font> Required field"));
The comment /*your view*/ you replace with a textview reference, edittext or whatever you use to set text
Further reading:
https://stackoverflow.com/a/9161958/6296561
The string of empty edittext might be null, which causes the issue. Try the following code.
if(imeNarucioca==null || imeNarucioca.equals("")){
Toast.makeText(Narudzbina.this, "Unesite ime", Toast.LENGTH_LONG).show();
}
else if(prezimeNarucioca==null || prezimeNarucioca.equals("")){
Toast.makeText(Narudzbina.this,"Unesite Prezime", Toast.LENGTH_LONG).show();
}
else if(telefonNarucioca==null || telefonNarucioca.equals("")){
Toast.makeText(Narudzbina.this,"Unesite kontakt telefon", Toast.LENGTH_LONG).show();
}
else if(adresaNarucioca==null || adresaNarucioca.equals("")){
Toast.makeText(Narudzbina.this,"Unesite adresu",Toast.LENGTH_LONG).show();
}
else if(gradNarucioca==null || gradNarucioca.equals("")){
Toast.makeText(Narudzbina.this, "Navedite grad", Toast.LENGTH_LONG).show();
}
else if(narucenaKolicina==null || narucenaKolicina.equals("")){
Toast.makeText(Narudzbina.this, "Navedite zeljenu kolicinu", Toast.LENGTH_LONG).show();
}
else{
startActivity(smsIntent);}
}
You should use isEmpty method provided in android.text.TextUtils. The whole description and implement of this method:
/**
* Returns true if the string is null or 0-length.
* #param str the string to be examined
* #return true if str is null or zero length
*/
public static boolean isEmpty(#Nullable CharSequence str) {
if (str == null || str.length() == 0)
return true;
else
return false;
}
So, to validate null or empty user input, you can do something like this:
if(android.text.TextUtils.isEmpty(imeNarucioca)){
// ...
}
So i'm using this, you can do with it what you like:
This is the method:
public static boolean checkEditTextIsEmpty(EditText... editTexts)
{
try
{
for (EditText editText : editTexts)
{
if (editText.getText().toString().trim().length() == 0)
{
Drawable d = _application.currentActivity.getResources().getDrawable(android.R.drawable.ic_dialog_alert);
d.setBounds(0, 0, d.getIntrinsicWidth()/2, d.getIntrinsicHeight()/2);
editText.requestFocus();
editText.setError(editText.getHint() + " is empty", d);
return false;
}
}
}
catch (Exception ignored)
{
return false;
}
return true;
}
This is a preview: (ignore my style and background)
This is how i implemented it:
if(checkEditTextIsEmpty(txtEmail, txtPassword))
{
//Do whatever if EditTexts is not empty
}
Just add this line in your Java file pro-grammatically,
adding mandatory field near Your Text view.
tv.setText (Html.fromHtml(YourText
+ " <font color='"
+ getResources().getColor(R.color.colorAccent) + "'>" + " * "
+ "</font>"));
add Required field instead of yourText field,
then use the required color from colors.xml

android: Log in Button

I'm having problem with my Log in activity.. the button will load the next activity even though no data inputted on the text field..
here's the code...
public void onButtonClick(View v){
if(v.getId()== R.id.Blogin) {
EditText a = (EditText)findViewById(R.id.TFusername);
String str = a.getText().toString();
EditText b = (EditText)findViewById(R.id.TFpassword);
String pass = b.getText().toString();
String password = helper.searchPass(str);
if(pass.equals(password))
{
Intent i = new Intent(User.this, Userlog.class);
i.putExtra("Username",str);
startActivity(i);
}
else
{
Toast temp = Toast.makeText(User.this, "Username and Password don't match!", Toast.LENGTH_SHORT);
temp.show();
}
Check for empty strings
replace
if(pass.equals(password))
with
if(pass.equals(password) && !TextUtils.isEmpty(str) && !TextUtils.isEmpty(pass))
This should work.
Cheers
You can check if a String is empty using the TextUtils class's isEmpty method, which is a static one.
// Checks if a username & a password were typed, then checks if password is correct
if(!TextUtils.isEmpty(str) && !TextUtils.isEmpty(pass) && pass.equals(password))
Notice that you are not checking whether the username is valid or not.
In you helper. searchPass(), do you return an empty string if no usrName is matched?If so, you have to check if the returned string is empty or you can return another special value :D

Xamarin.Android - Challenge with SQLite ORM queries

I've been working with Xamarin for a few weeks now and i'm trying to find the best practices for using SQLite ORM queries.I have a log in page which is launched first before users can access the app.I have the database created before this first activity comes to the screen and administrator log in details inserted into the user's table as soon as the tables are created.The point is,the admin is meant to log in and import an xml file containing all of the other user's personal information.This information is read from the file and saved to sqlite as well.
Next,the other users can log in after their details have been imported and saved successfully.My challenge is,at the point of logging in,i would like to verify the details as follows:
1.Compare the entered username with a single username from the db
**2.Check the password entered to see if it matches the username entered **
I'm currently using a select query to pull up all the passwords from the database,before comparing the two strings(from the db and from the edit text field).If it's a large db however,reading all the data will be quite expensive.How do i go about this?
How do i also look up the password for that username?
Below is my code:
namespace sample.NameSpace
{
[Activity (MainLauncher = true)]
public class MainActivity : Activity
{
Button login = FindViewById<Button> (Resource.Id.login);
try{
login.Click += (object sender, EventArgs e) => {
if (TextUtils.IsEmpty(userName.Text.ToString())) {
makeToast();
} else if (TextUtils.IsEmpty(password.Text.ToString())) {
makeToast();
} else {
returningUser = userName.Text.ToString().Trim();
returningUserPassword = password.Text.ToString().Trim();
}
//Check to see if the name is in the db already
List<string> allUsers = GetAllUserNames();
//Loop through the list of names and compare the retrieved username with the name entered in the text field
string retrievedDbName ="";
foreach(string name in allUsers )
{
retrievedDbName = name .Trim();
}
//Verify name
if(retrievedDbName .Equals(returningUser))
{
Toast.MakeText(this,
"Login Successful !", ToastLength.Short).Show();
Intent intent = new Intent (this, typeof(HomeActivity));
StartActivity (intent);
}
else
{
Toast.MakeText(this, "User Name or Password does not match", ToastLength.Short).Show();
}
};
} catch(Exception e){
logger.Exception (this, e);
}
public List<string>GetAllUserNames()
{
List<UserInfoTable> allUserNames = new List<UserInfoTable> ();
allUserNames = dataManager.GetSingleUserName ();
string name = "";
foreach(var UserName in allUserNames)
{
Console.WriteLine ("Usernames from db :" + name.ToString());
}
return allUserNames;
}
Then the DataManager class:
public List<UserInfoTable> GetSingleUserName()
{
UserInfoTable user = new UserInfoTable ();
using (var db = dbHandler.getUserDatabaseConnection ()) {
var userName = db.Query<UserInfoTable> ("select * from UserInfoTable where user_name = ?", user.USER_NAME);
return userName;
}
}
public bool CheckLogin(string user, string password)
{
bool valid = false;
using (var db = dbHandler.getUserDatabaseConnection ()) {
var user = db.Query<UserInfoTable> ("select * from UserInfoTable where user_name = ? and password = ?", user, password);
if (user != null) valid = true;
}
return valid;
}

android shared preference one key with multiple values

My query is straight forward, couldn't find answer across google:
For Example:
Repository 1 -> username1
-> password1
Repository 2 -> username2
-> password2
Repository 3 -> username3
-> password3
As mentioned above, I have a dialog box with three repositories. When user selects a repository automatically another dialog box pops up to enter username and password.
So, what i am trying to achieve is to save repository name, username and password in a shared preference with a single key.
I know how to create a shared pref object with a single key and value. What i am looking for is a shared pref obj with a single key and 3 values.
Is it really possible? If yes, you can show me some direction.
You can't store three values with a single key in the same SharedPreferences file, at least not on the abstraction level of the SharedPreferences object.
What you can do is store a JSON representation of the n 3-tuples (I think that's what you need). In other words, store a String which is made from a JSONArray of JSONObjects. This way, you need not care about separators, escaping and other such annoyances.
SharedPreferences prefs = getSharedPreferences(getPathForUser(username, password) + PREF_RESOURCES_NAME, MODE_PRIVATE);
public static String getPathForUser(String username, String password) {
String sUsername = null;
String sPassword = null;
// sUsername
if (username != null && username.trim().length() > 0) {
sUsername = username.trim();
} else {
sUsername = "defaultUsername";
}
// sPassword
if (password != null && password.trim().length() > 0) {
sPassword = password.trim();
} else {
sPassword = "defaultPassword";
}
try {
return URLEncoder.encode(sUsername, "UTF-8") + "__" + URLEncoder.encode(sPassword, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return "";
}
}

Categories

Resources