I'm kinda new and any help would be appreciated
Currently either it's filled it in or I'm getting a toast saying there is a nullpointer.
In the if else statement it will always jump to the else part. So the if doesn't seem to tihnk it's empty while that is what I'm getting in the toast(Created in the catch)
package com.example.domoticaapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class CreateProfile extends Activity implements OnClickListener
{
//Declare Variables
DBAdapter myDb;
EditText ipInput, nameInput;
Button save;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.create_profile);
ipInput = (EditText) findViewById(R.id.ipInput);
nameInput = (EditText) findViewById(R.id.nameInput);
save = (Button) findViewById(R.id.save);
save.setOnClickListener(this);
}
private void saveProfile()
{
String IP = ipInput.getText().toString();
String name = nameInput.getText().toString();
if(IP == null || name == null || IP == "" || name == "")
{
Toast.makeText(this, "Name and IP can't be empty!", Toast.LENGTH_SHORT).show();
}
else
{
try
{
myDb.insertRow(name, IP);
//Intent i = new Intent("com.example.domoticaapp.SQLView");
//startActivity(i);
}
catch(Exception e)
{
Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onClick(View v)
{
switch(v.getId())
{
case R.id.save:
saveProfile();
break;
}
}
}
Try this.
if(!IP.equals("") && !name.equals(""))
{
/** Your Code **/
}
else
{
Toast.makeText(this, "Name and IP can't be empty!", Toast.LENGTH_SHORT).show();
}
try this
if(TextUtils.isEmpty(name ) &&TextUtils.isEmpty(IP)){
Toast....
}else{
...
}
DBAdapter myDb;
myDb has not been intialised. You just declared it
Related
here is the java code :
package com.aliabbasi.mytamrin;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.text.DecimalFormat;
public class full extends AppCompatActivity {
EditText full_payment, cash_payment,remain_payment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_full);
Toast.makeText(this, "مقادیر را با دقت وارد کنید", Toast.LENGTH_LONG).show();
Button btn_cancel = findViewById(R.id.btn_cancel);
btn_cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent btn_cancel = new Intent(full.this, MainActivity.class);
startActivities(new Intent[]{btn_cancel});
}
});
try {
Button remain_check = findViewById(R.id.remain_btn);
remain_check.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
full_payment = findViewById(R.id.edt_full_payment);
cash_payment = findViewById(R.id.edt_cash_payment);
remain_payment = (EditText) findViewById(R.id.edt_remain);
Float a = Float.parseFloat(full_payment.getText().toString());
Float b = Float.parseFloat(cash_payment.getText().toString());
Float s = a - b;
String r = Double.toString(s);
remain_payment.setText(r);
}
});
} catch (Exception e) {
Toast.makeText(this, "خطایی رح داده" + e, Toast.LENGTH_LONG).show();
}
try {
EditText editText= (EditText) findViewById(R.id.edt_full_payment);
editText.addTextChangedListener(new MyNumberWatcher(editText));
}
catch (Exception e){
Toast.makeText(this, "ERR"+e, Toast.LENGTH_LONG).show();
}
try {
EditText editText= (EditText) findViewById(R.id.edt_cash_payment);
editText.addTextChangedListener(new MyNumberWatcher(editText));
}
catch (Exception e){
Toast.makeText(this, "ERR"+e, Toast.LENGTH_LONG).show();
}
/*try {
EditText editText= (EditText) findViewById(R.id.edt_remain);
editText.addTextChangedListener(new MyNumberWatcher(editText));
}
catch (Exception e){
Toast.makeText(this, "ERR"+e, Toast.LENGTH_LONG).show();
}*/
}
}
i try the double variable
there is no Error but program crashed when i press the remain_btn.
i check the Debug and find out there is a problem with this:
at com.aliabbasi.mytamrin.full$2.onClick(full.java:45).
andNumberFormatException** but IDK how to solve it.**
and i really like to know how fix this becase i stuck in this about 2 days...
thanks for reading ...
wish the best
code imag
You can do something like this. Remove that comma.
Float a = Float.parseFloat(full_payment.getText().toString().replace(",", ""));
I am building an app that toastes Welcome when only specific email and password is inputted. Otherwise it says Incorrect Email/password. But I don't understand what the problem with my code is. I think the problem is within string.gettext().toString(). I do not know how to use it in the if-else-loop...
package com.example.project2;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class Project2 extends AppCompatActivity {
public void login(View view) {
EditText email = (EditText) findViewById(R.id.emailEditText);
EditText password = (EditText) findViewById(R.id.passwordEditText);
Log.i("info","Button pressed!");
String Email = email.getText().toString();
String Password = password.getText().toString();
boolean email1 = Email.contains("example876#gmail.com");
boolean password1 = Password.contains("asad123");
if (email1){
Toast.makeText(this, "Welcome", Toast.LENGTH_LONG).show();
} else if (password1) {
Toast.makeText(this, "The method worked", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Incorrect Username/Password", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_project2);
}
}
Somebody plz help!!
THanks in advance...
I am trying to make the EditTextLayout makes an error message when they are empty and the app crashes
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class LoginActivity extends AppCompatActivity {
private TextInputLayout textInputEmail , textInputPassword;
private Button login;
String emailInput , passwordInput;
private FirebaseAuth auth;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
auth = FirebaseAuth.getInstance();
textInputEmail = (TextInputLayout) findViewById(R.id.login_email);
textInputPassword = (TextInputLayout) findViewById(R.id.login_password);
login = (Button)findViewById(R.id.login_button);
progressDialog = new ProgressDialog(this);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ConfirmInput();
progressDialog.setTitle("Singing in");
progressDialog.setMessage("Please wait while we sign you in");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
auth.signInWithEmailAndPassword(emailInput , passwordInput).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
progressDialog.dismiss();
Toast.makeText(LoginActivity.this, "Account Created successfuly", Toast.LENGTH_SHORT).show();
SendUserToMainActivity();
}else{
progressDialog.dismiss();
Toast.makeText(LoginActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
private void SendUserToMainActivity() {
Intent intent = new Intent(LoginActivity.this , MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
public boolean ValidateEmail(){
emailInput = textInputEmail.getEditText().getText().toString().trim();
if(emailInput.isEmpty()){
textInputEmail.setError("You Can't leave this Empty!");
return false;
}else{
textInputEmail.setError(null);
return true;
}
}
public boolean ValidatePassword(){
passwordInput = textInputPassword.getEditText().getText().toString();
if(passwordInput.isEmpty()){
textInputPassword.setError("You Can't leave this Empty!");
return false;
}else{
textInputPassword.setError(null);
return true;
}
}
public void ConfirmInput(){
if(!ValidateEmail() | !ValidatePassword()){
return;
}
}
}
java.lang.IllegalArgumentException: Given String is empty or null
at com.google.android.gms.common.internal.zzbq.zzgm(Unknown Source)
at com.google.firebase.auth.FirebaseAuth.signInWithEmailAndPassword(Unknown Source)
at com.example.bestever.snapchatclone.LoginActivity$1.onClick(LoginActivity.java:50)
at android.view.View.performClick(View.java:5184)
at android.view.View$PerformClick.run(View.java:20893)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5938)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
I tried also to change The TextInputLayout to TextInputEditText and nothing changed. I also tried to change my approach for checking if the TextInputLayout is empty, but it doesn't work
You should validate if textInputEmail.getEditText().getText() is null before retrieving the text from it, that might be the problem. Hope it works.
You can't call getText() function on null String.
Please use this method to implement it in the right way:
String emailInput;
emailInput = textInputEmail.getEditText().getText();
if (emailInput != null) {
emailInput = emailInput.toString().trim();
}
Or (My favorite way)
String emailInput = "";
try {
emailInput = textInputEmail.getEditText().getText().toString().trim();
} catch (IllegalArgumentException ex) { }
I'm new at programming. I'm doing a login system, but when I log in, I get that error. I don’t know how to solve it. And I have one more question: Is making a login system with chat and friends (add, Remove) system too hard?
Because I want to do that, but I just started programming one week ago, can I do this?
FATAL EXCEPTION: main
Process: complete.lyne.myapplication, PID: 18933
java.lang.ArrayIndexOutOfBoundsException: length=2; index=2
at complete.lyne.myapplication.Login$SolicitaDados.onPostExecute(Login.java:110)
at complete.lyne.myapplication.Login$SolicitaDados.onPostExecute(Login.java:91)
at android.os.AsyncTask.finish(AsyncTask.java:660)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:677)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Here is my code:
package complete.lyne.myapplication;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
// import br.com.simplepass.loading_button_lib.customViews.CircularProgressButton;
public class Login extends AppCompatActivity {
EditText loginEmail, loginSenha;
Button btLogar;
TextView refCadastrar;
String url = "";
String parametro = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
loginEmail = (EditText)findViewById(R.id.loginEmail);
loginSenha = (EditText)findViewById(R.id.loginSenha);
btLogar = (Button)findViewById(R.id.btLogar);
refCadastrar = (TextView)findViewById(R.id.refCadastrar);
refCadastrar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent abreCadastro = new Intent(Login.this, Cadastro.class);
startActivity(abreCadastro);
}
});
btLogar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ConnectivityManager connectivityManager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
String email = loginEmail.getText().toString();
String senha = loginSenha.getText().toString();
if(email.isEmpty() && senha.matches(".*[a-z].*")) {
loginEmail.setError("Insira seu endereço de Email.");
} else if (email.matches(".*[a-z].*") && senha.isEmpty()) {
loginSenha.setError("Insira sua Senha.");
} else if (email.isEmpty() && senha.isEmpty()) {
Toast.makeText(getApplicationContext(), "Nenhum campo pode ficar vazio.", Toast.LENGTH_LONG).show();
} else {
// Casa
url = "http://192.168.1.100/lyne/logar.php";
// Badran
// url = "http://172.16.2.15/lyne/logar.php";
parametro = "email=" + email + "&senha=" + senha;
new SolicitaDados().execute(url);
}
}
else {
Toast.makeText(getApplicationContext(), "Nenhuma conexão com a Internet foi encontrada.", Toast.LENGTH_LONG).show();
}
}
});
}
private class SolicitaDados extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
return Conexao.postDados(urls[0], parametro);
}
#Override
protected void onPostExecute(String resultado) {
if(resultado != null) {
if (resultado.contains("login_ok")) {
String[] dados = resultado.split(",");
Intent abreHome = new Intent(Login.this, Home.class);
abreHome.putExtra("idusu", dados[1]);
abreHome.putExtra("nomeusu", dados[2]);
startActivity(abreHome);
} else {
Toast.makeText(getApplicationContext(), "Usuário ou senha incorretos.", Toast.LENGTH_LONG).show();
}
}
}
}
#Override
protected void onPause() {
super.onPause();
finish();
}
}
You are asking for an index that doesn't exist inside of you array.
It seems like you're looking for two objects, not three, but you are looking in the wrong place.
You should edit your code to look like this:
abreHome.putExtra("idusu", dados[0]);
abreHome.putExtra("nomeusu", dados[1]);
You are splitting the string:
String[] dados = resultado.split(",");
And assuming there will be at least three pieces:
abreHome.putExtra("idusu", dados[1]);
abreHome.putExtra("nomeusu", dados[2]);
But looks like that's is not the case. Check for the length of dados before you go and access elements from it.
I'm trying to create an if statement, for example if the user doesn't type anything into the the two edit text's, then it displays a toast and resets everything. But for some reason, my code completely ignores this and just goes to the else statement instead.
Can anyone help?
My Code:
package com.gta5news.bananaphone;
import java.io.File;
import android.R.string;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class LogIn extends Activity implements OnClickListener {
Button send;
EditText user;
EditText pass;
CheckBox staySignedIn;
SharedPreferences shareduser;
SharedPreferences sharedpass;
public static String settings = "MySharerdUser";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
send = (Button) findViewById(R.id.bLogIn);
user = (EditText) findViewById(R.id.eTuser);
pass = (EditText) findViewById(R.id.eTpassword);
staySignedIn = (CheckBox) findViewById(R.id.Cbstay);
send.setOnClickListener(this);
SharedPreferences settings = getPreferences(MODE_PRIVATE);
String name = settings.getString("name", "");
String password = settings.getString("pwd", "");
user.setText(name);
pass.setText(password);
if (staySignedIn.isChecked()) {
SharedPreferences MySharedUser = getPreferences(MODE_PRIVATE);
settings.edit().putString("name", user.getText().toString())
.putString("pwd", pass.getText().toString()).commit();
}
if (user.length() > 0)
;
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bLogIn:
if (user.length() < 0)
Toast.makeText(this,
"Try to type in your username and password again!",
Toast.LENGTH_LONG).show();
else {
String u = user.getText().toString();
String p = pass.getText().toString();
Bundle send = new Bundle();
send.putString("key", u);
send.putString("key", p);
Intent a = new Intent(LogIn.this, FTPClient.class);
startActivity(a);
Toast.makeText(this, "Yay, you signed in!", Toast.LENGTH_LONG)
.show();
break;
}
}
}
}
if (user.length() == 0)
try it because user.length() is never come in Less Than Zero
You have to use
user.getText().toString().length()
Do you need an onClickListener for you checkbox???
checkbox.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Perform action on clicks, depending on whether it's now checked
if (((CheckBox) v).isChecked()) {
Toast.makeText(HelloFormStuff.this, "Selected", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(HelloFormStuff.this, "Not selected", Toast.LENGTH_SHORT).show();
}
}
});