Android - onClick errors in SMS app - android

I have a button that sends message - however the onClick feature in the onClickListener seems to give me a few errors when I tell it to disable the button when click, AND when I set toast to it. Oh, and the error underlines 'else' saying syntax error. (Other than that the code works fine and sends the SMS)
public void onClick(View v)
{
messageinfo mi = new messageinfo();
String message = txtMessage.getText().toString();
if (message.length()>0)
sendSMS(mi.SMSNO(), smsmessage);
Toast.makeText(getBaseContext(), "sending", Toast.LENGTH_SHORT).show();
myButton.setEnabled(false);
else
Toast.makeText(getBaseContext(), "enter your message", Toast.LENGTH_SHORT).show();
}
Is there an easy solution to this?

Through formatting your code I've noticed that it would appear that your if statement is failing.
You need to have { }s around the resulting code from an if statement, eg:
if(true){
line 1;
line 2;
line 3;
}
else {
line 1;
line 2;
line 3;
}
The only time you can miss out the { }s is when you've only got ONE statement following an if. This is always a bad idea however, its not much effort just to put in some { }s, and means that issues like this won't ever happen.
Clarification
The code in your question is running the if and if it matches it runs THE NEXT LINE. Then the code carries on OUTSIDE of the if clause (because of missing brackets)so then will run the next two lines REGARDLESS of the outcome of the if statement.
Then it encounters the else which its not expecting. Its supposed to be after either { .. } or directly after the FIRST statement after the if, so that's why it fails at the else.

Related

Android, using Toast inside onClickListener

I am trying to make a toast display some text given certain conditions inside an onClickListener. The app won´t run in the simulator, and I get the following error: "void cannot be converted to Toast"
I have searched around, and find several similar problems and solutions on this forum, but none of them applies completely to my problem. The others haven´t used the correct context in the statement, but I really mean that I do. (The name of the javafile (context) is: "Case1Activity") Can anyone help me with this?
I have simplified the code a bit:
public void onClick(View view) {
if (button1Pushed == false){
count++;
Toast toast = Toast.makeText(Case1Activity.this, "You are doing this in the right order!", Toast.LENGTH_LONG).show();
}
}
});
do it without assignment statement
Toast.makeText(Case1Activity.this, "You are doing this in the right order!", Toast.LENGTH_LONG).show();
apply it as.
Toast.makeText(Case1Activity.this, "You are doing this in the right order!", Toast.LENGTH_LONG).show();
if you want to use assignment operator then you can use below code
Toast toast = Toast.makeText(context, text, duration);
toast.show();
Dear Friend check below before eating Toast,
Your Toast (Incompatible types error) :
Toast toast = Toast.makeText(Case1Activity.this, "You are doing this in the right order!", Toast.LENGTH_LONG).show();
Normal Case (Standard Use):
Toast.makeText(Case1Activity.this, "You are doing this in the right order!", Toast.LENGTH_LONG).show();`
Special Case (if you need reference of Toast):
View toast = Toast.makeText(MainActivity.this, "You are doing this in the right order!", Toast.LENGTH_LONG).show();
because here ".show()" method is -
public void show () which
shows the view for the specified duration.
Thanks

Need help in my program in eclipse

public void click(View view) {
String one = "one";
EditText et = (EditText)findViewById(R.id.editText1);
String entered_text = et.getText().toString();
if(et.getText().toString() == one){
TextView tv1 = (TextView)findViewById(R.id.textView1);
tv1.setText("Correct!");
}
else {
TextView tv = (TextView)findViewById(R.id.textView1);
tv.setText(one+entered_text); }
}
This is a code snippet extracted from my program, I didn't post the whole program because it wasn't necessary, as the program runs fine without any runtime exceptions.
So, the program when executed on Eclipse doesn't show any errors and runs fine, but when run the, if condition et.getText().toString() == "one" always returns false even when the entered_text is one i.e.; it never prints "correct!" and the code always prints "one+entered_text" that is the statement in the else clause. And the interesting point is, if you enter one the output will be oneone, that is the else statement.
Please help me where I went wrong.
Thanks in advance.
Try this
if(et.getText().toString().equals(one)){
instead of
if(et.getText().toString() == one){
the better way is to compare string like et.getText().toString().equals("one");
also do et.getText().toString().trim().equals("one"); to avoid spaces error

Code not reaching if statement

I have the following code:
public void click(View v)
{
Button b = (Button) v;
TextView viewEditText = (TextView) findViewById(R.id.functionTextView);
String editText = viewEditText.getText().toString();
if (b.getId() == R.id.backspace)
{
if (viewEditText.length() > 0)
{
if (editText.substring(editText.length() - 1, editText.length()) == ".")
{
periodTrue = false;
}
viewEditText.setText(viewEditText.getText().toString().substring(0, viewEditText.length() - 1));
}
}
}
In this code I check to see if the character being backspaced is a period, if the previous condition is true. It sets the variable periodTrue to false. This tells the app that another period can be added.
Everything works with the backspace key as normal, except it never makes it inside the if statement where the variable is set. It throws no errors and I have checked with
viewEditText.append(editText.subString(editText.length()-1, editText.length()); to verify that the returned character is ".".
I don't know why it's not working, and it throws no errors or warnings either, on compile or run time. So I've come to you to see if a different perspective can show what I'm obviously doing wrong.
if (editText.substring(editText.length() - 1, editText.length()) == ".")
This won't work as you're comparing the references of the two Strings, which will be different. (More in-depth explanation in this question: How do I compare strings in Java?)
Use the following instead:
if (".".equals(editText.substring(editText.length() - 1, editText.length())))

How to return a toast to anything typed on EditText but a specific word?

I am currently developing my first android application, which is actually my first contact with java ever. Therefore, I suppose this question has an obvious answer to experienced developers, but I couldn't find anything at SO or anywhere else. The following EditText has two toasts (I'm not sure if that sounded right). One is shown if the user types a specific word (in this case, Please is shown if the user types Magic word and presses the button). I would like the another toast to appear if the user types anything else but that word (anything but "Magic word") when clicking the button.
EditText editText1 = (EditText) findViewById(R.id.editText1);
{
if(editText1.getText().toString().trim().equals("Magic word"))
{
Toast.makeText(MainActivity.this,
"Please", Toast.LENGTH_LONG).show();
}
}
else if (editText1.getText().toString().trim().equals())
{
Toast.makeText(MainActivity.this,
"You didn't say the magic word", Toast.LENGTH_LONG).show();
}
}
}
});
I apologize for my poor english. Hopefully, I made myself understood.
Thank you very much.
Following code give you the solution:
final EditText editText1=(EditText)findViewById(R.id.editText1);
Button btn=(Button)findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
final String edittext=editText1.getText().toString();
if(edittext.trim().equals("Magic word"))
{
Toast.makeText(MainActivity.this,
"Please", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(MainActivity.this,
"You didn't say the magic word", Toast.LENGTH_LONG).show();
}
}
});
More simple way!!
String hello = editText1.getText().toString();
and then,
Toast.makeText(MainActivity.this, "The text is" +hello , Toast.LENGTH_SHORT).show();
More accurately "Magic word" isn't a word, its two with a space. The first if statement will require the text in the EditText to be exactly that for the statement to be true. If you actually intended for "magic word" to merely be somewhere in the text typed into the EditText to show a Toast that says please, look into using String.contains() or regex for the first comparison.
For all other conditions there's no need to check the value of the EditText. In other words remove the second if just keep else as Luksprog mentioned.

Register not able to be done due to error checking in the if..else statement

I got problem with register. I use an if-else statement to check whether the user left any blank. If there is any blank, an error message will appear. The problem is, even with no blanks, all filled up, the error message still appears and thus prevents user from registering. I can't find any error.
Please help me spot my error.
package log1.log2;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Login extends Activity {
DBAdapter db = new DBAdapter(this);
/** Called when the activity is first created. */
private EditText etUsername;
private EditText etPassword;
private Button btnLogin;
private Button btnRegister;
private TextView lblResult;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Get the EditText and Button References
etUsername = (EditText)findViewById(R.id.usernametxt);
etPassword = (EditText)findViewById(R.id.passwordtxt);
btnLogin = (Button)findViewById(R.id.btnLogin);
btnRegister = (Button)findViewById(R.id.btnRegister);
lblResult = (TextView)findViewById(R.id.msglbl);
//Cursor c = (Cursor) db.getAllTitles();
//Button btnArrival = (Button) findViewById(R.id.btnRegister);
//btnArrival.setOnClickListener(this);
// Set Click Listener
btnRegister.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(Login.this,Register.class);
startActivity(intent);
}
});
btnLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
db.open();
Cursor c = (Cursor) db.getAllUser();
c.moveToFirst();
// Check Login
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
if(username.equals("") || password.equals(""))
{
Context context = getApplicationContext();
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, "FILL IN ALL FIELDS", duration);
toast.show();
}
else
{
if(username.equals(c.getString(1)))
{
if(password.equals(c.getString(2)))
{
Context context = getApplicationContext();
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, "LOGIN SUCCESS", duration);
toast.show();
long id;
id = db.insertTransaction(
new String(etUsername.getText().toString()));
Intent intent=new Intent(Login.this,Test.class);
startActivity(intent);
}
else
{
Context context = getApplicationContext();
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, "LOGIN FAIL", duration);
toast.show();
}
}
else
{
Context context = getApplicationContext();
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, "LOGIN FAIL", duration);
toast.show();
}
}
db.close();
}
});
}
}
Thank you very much.
Dayne,
I'm gonna try to help you here. Before I do, though, I want you to understand that you have been violating a lot of the conventional rules of stack overflow. I put a lot of time into trying to sort out your issues in this question, so I want to ask you to take a bit of time and try to understand what it is that you are doing wrong that makes others users on stack overflow (including me) very annoyed.
First, please don't use all caps. It is considered rude. Second, please don't post multiple questions on stack overflow that are all about the same issues. This is the 7th question that you have posted regarding this issue. That is also considered rude. Please post one question, and if the suggested answers do not work for you, then comment on them and ask for more help, specifying what part of their answer you used and what problems you are having still. Third, please do not post your entire file. If your entire file is needed the the commentors will ask you to post it, but don't post it up front. Consider that the people who are helping you with your questions are NOT getting paid. They are doing it for free, as a service to people trying to learn how to program. Posting your entire file up front is like you are asking someone to do your work for you, and the users on here are not interested in doing your work, they are interested in helping people learn. We want you to be able to do this stuff yourself. If you just want a solution that works and are not interested in learning why it works, you would be better off choosing a different community of people to ask questions to. Lastly, please try to research more! A lot of your questions betray that you are utterly clueless about how certain things work. Please, rather than simply posting on stackoverflow again and again, go spend a few hours reading up on how to create a login system in Android
That being said, you seem like a nice enough person to me. It looks like you are new to stack overflow and new to programming in general, so I am willing to forgive all those things you did that annoyed me, as long as you do your best to not do them again.
General Issues with your code
Ok, let's get into the general point of your code code. I have tried to fix your code to the point that it compiles and works. However, I want to point out that what you are trying to do is largely useless for any practical program. If I understand you correctly, you are trying to have a user login to some service or be able to register for that service. However, it looks like you are trying to use a database on the phone to log users in or register new users. If you have a database of usernames and passwords stored on a phone, then there is no way to have another user login. Let me give you an example. User A has a phone, and user B has a phone. If the database of usernames and passwords is stored on user A's phone, then how will user B login? Additionally, how would user B register for the service? There is reliable way to communicate between the two phones. On top of that, what if user A drops their phone and it breaks? Does that mean that your entire service is unavailable?
What you need to do, if you are providing login/registration for some service, is to have a server set up somewhere that phones can contact to perform login operations or registration operations. Setting up a server and a login/registration system is a big project, and you will need to read up on how to do that before anyone can really help you - right now I dont think you would understand most of the advice they would give you.
That being said, it is possible that you just want to get this local database login system to work for some reason (perhaps you just want something to work, all programmers have had a point where nothing they do seems to work and you are desperate to make anything work ;) ). So, let's see if we can make it work . . .
Separation of responsibility
You are trying to solve 2 main problems (I am ignoring registration for now. If you understand login then you can figure out registration). First, you want to provide some feedback to the user if they do not give you a username or a password. Second, you want to check if that person has provided a correct username / password combination. Right now you are trying to solve both of these problems within the Login Activity. I recommend separating these responsibilities - let the Login class handle providing feedback, and slightly modify your DBAdapter class so that it can handle checking the username/password.
Modify your DBAdapter class and add the following method:
public boolean isValidUser(String username, String password) {
Cursor c = <your SQLiteDatabase>.rawQuery("SELECT username FROM Users WHERE username='?' AND password='?'", new String[] {username, password});
boolean result = c.moveToFirst();
return result;
}
Please note that this method has a lot of problems, and should not be used in production code. I am assuming you just want this to work, and you don't care if it is perfect. If you can get this all working, perhaps ask a new question focused on verifying that a username / password combination is correct.
Note that you need to change the part that says <your SQLiteDatabase> to contain your database name.
Once you have added this method, your DBAdapter class can, given a username and password, inform you if that username and password combination is valid.
Making the Login Activity
Change the btnLogin onClickListener to this:
btnLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
if (username.trim().equals("") || password.trim().equals("")) {
Context context = getApplicationContext();
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, "FILL IN ALL FIELDS",
duration);
toast.show();
// Rather than having a huge else {} block, why not just add a
// return statement here? Then the rest of your code is a bit
// cleaner!
return;
}
db.open();
if (db.isValidUser(username, password))
{
Context context = getApplicationContext();
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context,
"LOGIN SUCCESS", duration);
toast.show();
Intent intent = new Intent(Login.this, Test.class);
startActivity(intent);
} else {
Context context = getApplicationContext();
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, "LOGIN FAIL",
duration);
toast.show();
}
db.close();
}
});
That should be all you need to get this to work! Note, however, that you didn't post your DBAdapter class here. I didn't want to look through the 7 posts to find it. Given the state of this post's code and the one other I looked at, it's likely that there are some errors in your DBAdapter. Read this section on the Android docs and try to debug that part yourself :) If you get stuck, you can ask a question about how to build a database on Android, and NOT a question about how to build a database/login on Android, since your login code should be mostly workable if you use the code I pasted here!
Final Points
Please consider the following comments I made when originally looking at your code
// NO!!!! Do not do this. You will end up with a problem
// very similar to http://stackoverflow.com/questions/3352957/
// why-does-not-this-work-android-oncreate/3352978#3352978
// Instead, say db = new DBAdapter(this) inside of the onCreate() method!
DBAdapter db = null; // new DBAdapter(this);
Also,
// This is an absolutely huge inner-class. It would be a lot better
// to extract this into a private member variable, by saying
// OnClickListener foo = new OnClickListener() { <put all code here> };
// btnLogin.setOnClickListener(foo);
btnLogin.setOnClickListener(new OnClickListener() {
Also,
// No!! If you are calling getAllUser(), you are likely returning a Cursor that points
// to a ton of users. The way your code is now, you are returning a list of all users
// in the application, and then checking to see if this data entered matches the first
// user. This would never work! If you have more than one user, then you need to check
// if the data entered matches ANY of your users. I am removing this code
// db.open();
// Cursor c = (Cursor) db.getAllUser();
// c.moveToFirst();
Cheers,
Hamilton
I think you need to do username.getText().equals(""), not just .equals because in that case you try to compare the empty string to the EditText object...

Categories

Resources