I have a class named MyPrimaryClass, this class has a button witch when pressed, creates an Intent with the class myClassForResult.
I use this to start it:
startActivityForResult(myIntentOfMyClassForResult, ACTIVITY_EDIT_BTEXT);
Both MyPrimaryClass, and myClassForResult extends Activity.
So, when I call Toast.makeText within the myClassForResult, with the text parameter of R.string.my_resource_string, it gives me Force Close!
I have tried this:
Context c = myClassForResult.this;
Toast toast = Toast.makeText(c,
c.getResources().getString(R.string.my_resource_string),
Toast.LENGTH_SHORT);
toast.show();
Also this: c = getApplicationContext()
Also this: c = getBaseContext()
Also this:
Context c = MyPrimaryClass.this;
Toast toast = Toast.makeText(c,
R.string.my_resource_string,
Toast.LENGTH_SHORT);
toast.show();
If I use an inline string, like "My toast Text!", it works. But i need to get a string from the resources.
-Problem solved:
To solve the problem I changed the duration of the Toast to Toast.LENGTH_LONG
The string R.string.my_resource_string value is "The title is empty"
When I change its value to "The title", it worked properly, so I guess the string was too long for the Toast.LENGTH_SHORT duration.
But when i change the duration to Toast.LENGTH_LONG, I could use the long string.
Context c = MyPrimaryClass.this;
Toast toast = Toast.makeText(c,
R.string.my_resource_string,
Toast.LENGTH_LONG);
toast.show();
One thing to note:
Toast toast = Toast.makeText(c,
c.getResources().getString(R.string.my_resource_string),
Toast.LENGTH_SHORT);
toast.show();
Can be simplified into:
Toast.makeText(c,
c.getResources().getString(R.string.my_resource_string),
Toast.LENGTH_SHORT).show();
This saves you an object reference that you do not need.
One thing you need to understand is that whenever you reference you R in your package (not android.R.) you will have access to your resources as long as you have Context.
Update
After realizing what you are using this for I would recommend that you
change your approach, while this is in fact possible, your approach isn't ideal for something so simple.
The method startActivityForResult(xx) is typically when you want to start an application that is outside of your package for a result.
For instance: if I wanted to retrieve a barcode from a product, then I'd start an Intent to that barcode class, indirectly through an action. Then I'd retrieve the data through using onActivityResult(xx).
it makes No Sense to do this for your own classes.
Try:
Toast.makeText(this, this.getString(R.string.my_resource_string), Toast.LENGTH_SHORT);
#dilipkaklotar Answered correctly but a few changes needs to be done:
this is how it worked for me
Toast.makeText(getApplicationContext(),
getApplicationContext().getResources().getString(R.string.message),
Toast.LENGTH_SHORT).show();
the getResources has no parenthesis ().
and at the end is .show(); not toShow().
but it's correct. so thank you very much.
Toast.makeText(getApplicationContext(), getApplicationContext().getResources.getString(R.string.imgval), Toast.LENGTH_SHORT).toShow();
Related
I am new to Android. So, after clicking a button a toast message appears. I would like to store the toast message in a variable as a string after the message appears.
I have viewed this: Is it possible to get the value of string of Toast.makeText()?
In the solution provided there, he has created a variable name myToast. I have more than one toast but only one toast will appear when the button is clicked. I would like to store that particular toast as a string.
Thanks in advance!!
I think you can previously create one general string variable which will be changed when some button will be clicked and then you can show this variable in the toast which will appear. For example:
var selectedString:String = ""
then assign another value:
selectedString = "some_data"
and then show it in the toast:
Toast.makeText(this, selectedString , Toast.LENGTH_SHORT).show()
UPDATE
In general after clicking on button you will assign the latest string which will be represented in toast. So after that, you only need to analyse stored variable:
when(selectedString){
"test_1" -> moveFun(1)
"test_2" -> moveFun(1)
}
and then we have to create function for moving to next screen:
fun moveFun(toWhich:Int)
{
var intent:Intent?=null
when(toWhich){
1-> intent = Intent(this, FirstActivity::java.class)
2-> intent = Intent(this, SecondActivity::java.class)
}
if(intent!=null){
startActivity(intent)
}
}
UPDATE 2.0
Example of assigning value to selectedString:
selectedString = if(success_condition){
"good"
}else{
"bad"
}
then show it in Toast:
Toast.makeText(this, selectedString , Toast.LENGTH_SHORT).show()
and then analyse it :)
I'm trying to check the editText condition. In the code below, I declared a setOnClickListener method to check the condition of editText. If condition is true, I want to print toast message, change the activity and to output a sound. If condition fails, it should toast a single message. In both cases if it's true or not, it prints me only "Incorect" no matter if editText is correct.
What I am doing wrong?
public void next(View v){
final MediaPlayer correctSound = MediaPlayer.create(this, R.raw.correctsound);
Button playCorrectSound = (Button) this.findViewById(R.id.angry_btn1);
final EditText editTextt = (EditText) findViewById(R.id.editText);
playCorrectSound.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editTextt.setVisibility(View.INVISIBLE);
if(editTextt.getText().toString() == "string")
{
Toast.makeText(getApplicationContext(), "Correct", Toast.LENGTH_SHORT).show();
correctSound.start();
Intent i = new Intent(Hereuu.this, MainActivity.class);
startActivity(i);
} else {
Context context = getApplicationContext();
CharSequence text = "Incorect";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
editTextt.setVisibility(View.VISIBLE);
}
});
}
Like everyone had said, you
Basically, when you use == operator, your are checking if the reference for object are the same/equals. When you use .equals(String), the method checks the content.
tip:
When your are working with Strings, remember to avoid NullPointerException situations. So,you should write "constant".equals(editTextValue) instead of editTextValue.equals("constant")
The link bellow will help you to understand how String objects and String content work:
Java String.equals versus ==
regards
in java you need to compare strings using equals method instead of ==
check this topic for more details
I would suggest you to take some basic JAVA lessons. That will immensely help you.
For now, the problem is in the way you are checking equality of the strings. You do not use == with strings, you use String#equals() method. So,
Change
editTextt.getText().toString() == "string"
to
editTextt.getText().toString().equals("string")
Make sure to compare strings in java with .equals and not ==. Use this if statement:
if(editTextt.getText().toString().equals("string"){
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
I'm trying to use a Toast message inside a listener method, but I get an error saying something like: Toast is not applicable for the argument.. I don't understand this and can't solve this problem without some help? Thanks!
// Button 1
button_1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//text_1.setText("New text for first row!"); // Change text
Toast.makeText(this, "You have clicked on number 1", Toast.LENGTH_LONG).show();
if(controlImage_1)
{
image_1.setImageResource(R.drawable.android_1b); // Change image
controlImage_1 = false;
}
else
{
image_1.setImageResource(R.drawable.android_1a); // Change image
controlImage_1 = true;
}
//Toast.makeText(this, "Your download has resumed.", Toast.LENGTH_LONG).show();
}
});
Try it:
Toast.makeText(**YourClassName.this**, "You have clicked on number 1", Toast.LENGTH_LONG).show();
Without * =)
Toast.makeText(this, "You have clicked on number 1", Toast.LENGTH_LONG).show();
Your this in this statement refers to the View.OnClickListener you created. Read more on anonymous inner classes.
Use MyActivity.this instead
You need to pass in the Context of the current Activity as the first argument. You can't just say this in this case because it is not referring to the application context. You can either create a variable in your on create and use that context or just do this...
Toast.makeText([CLASS_NAME].this, "You have clicked on number 1", Toast.LENGTH_LONG).show();
Replace [CLASS_NAME] with the class that is extending Activity
Try getApplicationContext() as first argument for Toast.makeText or MyActivity.this
here in your code , this refers to the View
Also, if button_1 needs to have onclick listener by default and you are using API > 7,its nice to define onclick="myclickfunction" in the layout itself. Cleans up your code and easy to modify...
Because you are using it in the onClick Listener method, you cannot use only this as the first parameter.
Toast.makeText(ClassName.this, "You have clicked on number 1", Toast.LENGTH_LONG).show();
Use your classname.this as the first parameter.
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...