am presently trying to get a response from a server which contains a response code of "00,02" i used an if and else if statement to perform an action for each of this response but am getting null pointer for the first if statement
if (str.equalsIgnoreCase("02")){
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}else if(str.equalsIgnoreCase("00")){
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
A null-safe way of comparing strings would be:
if ("02".equalsIgnoreCase(str)) {
...
}
So just flip the strings in each of your conditions and you should be good to go!
Update your condition like this
if(str == null || str.length() == 0){
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
else if (str.equalsIgnoreCase("02")){
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}else if(str.equalsIgnoreCase("00")){
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
else{
// Unknown code from server
}
You can use the TextUtils.isEmpty(str) function like so:
if (!TextUtils.isEmpty(str)){
if (str.equalsIgnoreCase("02")){
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}else if(str.equalsIgnoreCase("00")){
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
}
This function basically does this for you:
public static boolean isEmpty(#Nullable CharSequence str) {
if (str == null || str.length() == 0)
return true;
else
return false;
}
Which you could've done yourself, but it might be clearer this way.
Related
I'm using while loop and inside am using two if statements.
while(cr.moveToNext()){
if(cr.getCount() > 0){
if((cr.getString(5).equals(username)) && cr.getString(6).equals(password)
&& cr.getString(14).equals("success")) {
String un = cr.getString(2);
String uc = cr.getString(1);
String rc = cr.getString(4);
......................
Toast.makeText(LoginActivity.this, "Successfully Logged In", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), Dashboard.class);
startActivity(intent);
} else{
Toast.makeText(LoginActivity.this, "Invalid Login", Toast.LENGTH_SHORT).show();
}
}
}
In this scenario, if I passed wrong value "Invalid Login" is executing many times [as it is inside while loop] and If I pass correct values both successfully login and Invalid login message is showing. How to make if condition to be properly work in this type of scenario...
Assuming you want to check that everything is in order before starting the activities you can do the loop twice, like below.
I also used do while, so as not to skip the first result.
private void handleCursor(Cursor cr){
boolean everythingGood = true;
do{
if (cr.getCount() > 14) { // <- if you are using cr.getString(14)
//to get "Success" string, then you should
//check for that too
if (!checkSuccess(cr) )
everythingGood = false; }
}else {
//not enough columns received.. assumed login fail.
//do your failure workflow
everythingGood = false;
}
} while(cr.moveToNext() && everythingGood);
if(everythingGood){
//second loop (no need to check any more, just spawn the activities)
cr.moveToFirst();
do{
createActivities(cr);
}while(cr.moveToNext();
}else {
handleFailure();
}
}
I moved your check condition out to another function to make it easier to see the while loop
private boolean checkSuccess(Cursor cr){
return cr.getString(5).equals(username)) && cr.getString(6).equals(password)
&& cr.getString(14).equals("success");
}
you can use break; or you can use a boolean flag variable , at first keep it true, then enter the conditions if it is true and once entered make the flag variable false in side that condition.
Boolean isValid;
isValid = true;
while(cr.moveToNext())
{
if (cr.getCount() > 0)
{
if ((cr.getString(5).equals(username))
&& cr.getString(6).equals(password) && cr.getString(14).equals("success"))
{
if (isValid)
{
isValid=false;
String un = cr.getString(2);
}
}
else { .......... }
}
}
I'm using if else and writing down some codes suddenly happens the else said the branch is never used... but it should work.
The statement looks like this
JOptionPane.showConfirmDialog(null,full_name+"\n"+number_age+"\n"+gender+"\n"+address+
"\n"+birthday+"\n"+cell_no,"CHECK INFORMATION!",JOptionPane.YES_NO_OPTION);
if(true){
JOptionPane.showMessageDialog(null,"Thank you for Entering");
}else{
JOptionPane.showMessageDialog(null,"Please Retry");
}
Check JOptionPane.showConfirmDialog response and compare with JOptionPane.YES_NO_OPTION:
int answer = JOptionPane.showConfirmDialog(null,full_name+"\n"+number_age+"\n"+gender+"\n"+address+
"\n"+birthday+"\n"+cell_no,"CHECK INFORMATION!",JOptionPane.YES_NO_OPTION);
if (JOptionPane.YES_OPTION == answer)) {
JOptionPane.showMessageDialog(null,"Thank you for Entering");
} else {
JOptionPane.showMessageDialog(null,"Please Retry");
}
hell... I in my code prevent duplicate entries but when update any field in this row tell my this name exist Although I'm in same row
as example have column firstName value = Mohamed ,column lastName value = taha and column Age value 25 when update Age tell my this firstName exist.
How to Solution this problem ?
This is my method:
public void saveStore(){
String namePermission =ETNamePermission.getText().toString().trim();
String notes = ETNotesPermission.getText().toString().trim();
boolean isExist = dbHelper.isExistNamePErmission(namePermission);
if ( intent == null && TextUtils.isEmpty(namePermission)|| TextUtils.isEmpty(namePermission) ){
ETNamePermission.requestFocus();
ETNamePermission.setError(getString(R.string.error_empty_text));
return;
}
if (intent == null) {
if (isExist ==true){
ETNamePermission.requestFocus();
ETNamePermission.setError(getString(R.string.error_exist_permission));
return;
}
ItemsStore itemSavePErmission = new ItemsStore();
itemSavePErmission.setNamePermission(namePermission);
itemSavePErmission.setNotes(notes);
if (itemSavePErmission == null) {
Toast.makeText(getContext(), getString(R.string.error_save_permission), Toast.LENGTH_LONG).show();
}else {
dbHelper.addPermission(itemSavePErmission);
Toast.makeText(getContext(), getString(R.string.save_permission), Toast.LENGTH_LONG).show();
dialog.dismiss();
}
}else {
ItemsStore itemUpdatePermision = new ItemsStore();
itemUpdatePermision.setId(intent.getInt(ID_PERMISSION));
itemUpdatePermision.setNamePermission(namePermission);
itemUpdatePermision.setNotes(notes);
boolean isExistForUpdated = dbHelper.isNamePermissioneUsedDailyMovements(intent.getInt(ID_PERMISSION));
if (isExistForUpdated == true){
Toast.makeText(getContext(), getString(R.string.this_permission_not_updated), Toast.LENGTH_SHORT).show();
return;
}
if (itemUpdatePermision != null){
dbHelper.updatePermission(itemUpdatePermision);
Toast.makeText(getContext(), getString(R.string.update_permission), Toast.LENGTH_LONG).show();
dialog.dismiss();
}else {
Toast.makeText(getContext(), getString(R.string.error_update_permission), Toast.LENGTH_LONG).show();
}
} }
Use Sqlite replace() method
db.replace(TABLE_NAME, null, contentValues);
But your table should have a unique or primary key. And replace method will check if a row exist with the given primary key. If exist the it will replace with updated value, if not then it will insert a new row with the given values.
Check this tutorial to learn about replace() method.
private void EnterbuttonActionPerformed(java.awt.event.ActionEvent evt) {
if (Usernamefield.getText().equalsIgnoreCase("User"));
if (Passwordfield.getText().equalsIgnoreCase("420"));
{
JOptionPane.showMessageDialog(null, "Welcome, User!");
}
else
{
JOptionPane.showMessageDialog(null, "Wrong Username/Password!");
}
It says that an else statement cannot work without an if, there are clearly 2 if statements however. I would like to create a simple log-in GUI in Java.
change
if (Usernamefield.getText().equalsIgnoreCase("User"));
if (Passwordfield.getText().equalsIgnoreCase("420"));
to
if (Usernamefield.getText().equalsIgnoreCase("User") &&
Passwordfield.getText().equalsIgnoreCase("420"))
{
JOptionPane.showMessageDialog(null, "Welcome, User!");
}
else
{
JOptionPane.showMessageDialog(null, "Wrong Username/Password!");
}
You want both conditions to be true in order to accept the user.
And don't put a ; at the end of an if condition, since that makes it an empty if statement that does nothing (that's the reason your else had no matching if).
Try the below code.
private void EnterbuttonActionPerformed(java.awt.event.ActionEvent evt) {
if (Usernamefield.getText().equalsIgnoreCase("User") && Passwordfield.getText().equalsIgnoreCase("420"))
{
JOptionPane.showMessageDialog(null, "Welcome, User!");
}
else
{
JOptionPane.showMessageDialog(null, "Wrong Username/Password!");
}
Not getting any errors im just stumped on this friggin if statement. I want the if statement to basically say if a check box is not checked and 3 EditTexts are empty then print a toast. Otherwise dont print the toast and continue to the next activity. First I turn the value of the checkbox into either t/f for true/false then execute my if statements as the following.
CheckBox noPtD1 = (CheckBox) findViewById(R.id.noPTD1);
String noPt_D1 = "f";
if (noPtD1.isChecked()) {
noPt_D1 = "t";
}
if (noPt_D1.equals("f") && day1_inst.equals("") || day1_uniform.equals("") ||
day1_location.equals(""))
{
Toast.makeText(getApplicationContext(), "Please Enter All Data Or Select the NO PT THIS DAY
checkbox!", Toast.LENGTH_LONG).show();
}
if(noPt_D1.equals("t") || !day1_inst.equals("") && !day1_uniform.equals("") &&
!day1_location.equals(""))
{
//PASS VARIABLES WITH INTENT
Intent intent = new Intent (OneWeekPlan_Start_Btn.this, Week1Day2.class);
//PASS VARIABLES FOR DAY 1
intent.putExtra("noPt_D1", noPt_D1);
intent.putExtra("day1_inst", day1_inst);
intent.putExtra("day1_uniform", day1_uniform);
intent.putExtra("day1_location", day1_location);
intent.putExtra("d1hours", d1hours);
intent.putExtra("d1min", d1min);
intent.putExtra("d1x1", d1x1);
intent.putExtra("d1x2", d1x2);
intent.putExtra("d1x3", d1x3);
intent.putExtra("d1x4", d1x4);
startActivity(intent);
}
This is working except for then I check the checkbox and and start the next activity with a button the next activity pops up like it is supposed to but the toast still appears. What did I mess up?
I got it I posted my answer below. But to rephrase exactly what my intent was:
If the user DOES NOT check the checkbox and leaves all 3 inputtexts blank show the toast and dont continue to next activity.
If the user DOES check the checkbox then DONT show the toast and continue to next activity.
Use brackets inside if statement
if (noPt_D1.equals("f") && (day1_inst.equals("") || day1_uniform.equals("") ||
day1_location.equals("")))
{
}
if(noPt_D1.equals("t") || (!day1_inst.equals("") && !day1_uniform.equals("") &&
!day1_location.equals("")))
{
}
You are making minor mistake in condition PLUS you need to use if - else block instead of 2 if blocks
//surround all && conditions inside separate braces
if (noPt_D1.equals("f") && (day1_inst.equals("") || day1_uniform.equals("") ||
day1_location.equals("")))
{
//show toast
}
else if(noPt_D1.equals("t") || (!day1_inst.equals("") && !day1_uniform.equals("") &&
!day1_location.equals("")))
{
//start activity
}
Hope this helps.
also try this. and its better to avoid including special characters for ur class name
if ("f".equals(noPt_D1) && "".equals(day1_inst) || "".equals(day1_uniform) ||
"".equals(day1_location))
{
Toast.makeText(getApplicationContext(), "Please Enter All Data Or Select the NO PT THIS DAY
checkbox!", Toast.LENGTH_LONG).show();
}
if("t".equals(noPt_D1) || !"".equals(day1_inst) && !"".equals(day1_uniform) &&
!"".equals(day1_location))
{
//PASS VARIABLES WITH INTENT
Intent intent = new Intent (OneWeekPlan_Start_Btn.this, Week1Day2.class);
//PASS VARIABLES FOR DAY 1
intent.putExtra("noPt_D1", noPt_D1);
intent.putExtra("day1_inst", day1_inst);
intent.putExtra("day1_uniform", day1_uniform);
intent.putExtra("day1_location", day1_location);
intent.putExtra("d1hours", d1hours);
intent.putExtra("d1min", d1min);
intent.putExtra("d1x1", d1x1);
intent.putExtra("d1x2", d1x2);
intent.putExtra("d1x3", d1x3);
intent.putExtra("d1x4", d1x4);
startActivity(intent);
}
Try to check EditText values via length() of String value. Secondly put && operator in if statement because you said in your question: if a check box is not checked and 3 EditTexts are empty then print a toast. Otherwise dont print the toast and continue to the next activity.
if (noPt_D1.equals("f") && day1_inst.trim().length() == 0 && day1_uniform.trim().length() == 0 &&
day1_location.trim().length() == 0)
{
Toast.makeText(getApplicationContext(), "Please Enter All Data", Toast.LENGTH_LONG).show();
}
else
{
Intent intent = new Intent (OneWeekPlan_Start_Btn.this, Week1Day2.class);
intent.putExtra("noPt_D1", noPt_D1);
intent.putExtra("day1_inst", day1_inst);
intent.putExtra("day1_uniform", day1_uniform);
intent.putExtra("day1_location", day1_location);
intent.putExtra("d1hours", d1hours);
intent.putExtra("d1min", d1min);
intent.putExtra("d1x1", d1x1);
intent.putExtra("d1x2", d1x2);
intent.putExtra("d1x3", d1x3);
intent.putExtra("d1x4", d1x4);
startActivity(intent);
}
EDIT:
Make sure you should declare your Strings which I am assuming are:
String day1_inst = your_editText_inst.getText().toString();
String day1_uniform = your_editText_uniform.getText().toString();
String day1_location = your_editText_location.getText().toString();
String noPt_D1 = "f";
if(your_check_box.isChecked())
{
noPt_D1 = "t";
}
else
{
noPt_D1 = "f";
}
Try using an OnCheckedChangeListener Listener, like whats shown below :
CheckBox noPtD1 = (CheckBox) findViewById(R.id.noPTD1);
String noPt_D1 = "f";
noPtD1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
noPt_D1 = "t";
} else {
noPt_D1 = "f";
}
}
});
Replace getApplicationContext() with this if you are in activity. getActivity() if you're in fragment.
Just figured it out thanks to M S Gadag =)
Basically I took the if statements and put the startActivity if statement on top. Then I added a variable to show that that statement had already been executed. Then I used that variable to start another if statement to decide whether or not to show the toast.
int showToast = 0;
if("t".equals(noPt_D1) || !"".equals(day1_inst) && !"".equals(day1_uniform) &&
!"".equals(day1_location))
{
//PASS VARIABLES WITH INTENT
Intent intent = new Intent (OneWeekPlan_Start_Btn.this, Week1Day2.class);
//PASS VARIABLES FOR DAY 1
intent.putExtra("noPt_D1", noPt_D1);
intent.putExtra("day1_inst", day1_inst);
intent.putExtra("day1_uniform", day1_uniform);
intent.putExtra("day1_location", day1_location);
intent.putExtra("d1hours", d1hours);
intent.putExtra("d1min", d1min);
intent.putExtra("d1x1", d1x1);
intent.putExtra("d1x2", d1x2);
intent.putExtra("d1x3", d1x3);
intent.putExtra("d1x4", d1x4);
startActivity(intent);
showToast = 1;
}
if ("f".equals(noPt_D1) && "".equals(day1_inst) || "".equals(day1_uniform) ||
"".equals(day1_location))
{
if (showToast !=1)
{
Toast.makeText(getApplicationContext(), "Please Enter All Data Or Select the NO PT THIS
DAY checkbox!", Toast.LENGTH_LONG).show();
}
}