Here's how I implement Toast:
if ((name == "") || (pass == "")){
Toast invalidLoginToast = new Toast.makeText(this, "aaa", 3).show();
} else {
Intent intent = new Intent (this, AnnouncementsActivity.class);
String deviceId = Secure.getString(this.getContentResolver(), Secure.ANDROID_ID);
intent.putExtra("NAME", name);
intent.putExtra("ID", deviceId);
startActivity(intent);
}
But I get the error
Error:(34, 48) error: cannot find symbol class makeText
Neccessary imports are already made. Am I sending wrong parameters into the method?
Instantiate a Toast object with one of the makeText() methods. This
method takes three parameters: the application Context, the text
message, and the duration for the toast. It returns a properly
initialized Toast object. You can display the toast notification with
show();
Toast.makeText(context, text, duration)
Read official guideline about Toast .
Toast.makeText(CurrentActivityName.this,"aaa",Toast.LENGTH_SHORT).show();
Just do Toast.makeText(this, "aaa", LENGHT_SHORT).show();
This line is wrong,
Toast invalidLoginToast = new Toast.makeText(this, "aaa", 3).show();
Replace it with
Toast.makeText(this, "aaa", 3).show();
Toast is having makeText method as static, and you can call it from the class name, don't call it the way you are calling it(i.e by new operator).
For further info, please visit the official documentation
Remove new keyword in front of Toast initialization.
use
Toast invalidLoginToast = Toast.makeText(this, "aaa", 3).show();
You don't need to use new keyword while creating Toast as it is provided by factory method inside Toast which does that for you.
Instantiate a Toast object with one of the makeText() methods. This
method takes three parameters: the application Context, the text
message, and the duration for the toast. It returns a properly
initialized Toast object. You can display the toast notification with
show()
Toast.makeText(context, text, duration);
context
getApplicationContext() - Returns the context for all activities
running in application.
getBaseContext() - If you want to access Context from another context
within application you can access.
getContext() - Returns the context view only current running activity.
text
text - Return "STRING" , If not string you can use type cast.
(string)num // type caste duration
duration
Toast.LENGTH_SHORT - Toast delay 2000 ms predefined
Toast.LENGTH_LONG - Toast delay 3500 ms predefined
milisecond - Toast delay user defined miliseconds (eg. 4000)
if ((name.equals("")) || (pass.equals(""))){
Toast.makeText(this,"aaa",Toast.LENGTH_SHORT,).show();
}
Toast invalidLoginToast = new Toast.makeText(this, "aaa", 3).show();
just remove the part (Toast invalidLoginToast = new) from your coding as you don't need to create object to Toast class to access makeText function, because its static it can be accessed directly using class name itself as Toast.makeText
just write it as
Toast.makeText(this, "aaa", 3).show();
(or)
Toast.makeText(this,"aaa",Toast.LENGTH_SHORT).show();
Related
EDIT :
*The entire issue was that since i miss-read .makeText for .makeToast, since
i have corrected this i have found that both of the previous attempts actually work for my app. *
I'm having issues implementing Toast.makeToast method in my android app :
I tried
public void onRightCardExit(Object dataObject) {
Toast.makeToast(MainActivity.this, "Right", Toast.LENGTH_SHORT).show();
}
as well as
public void onLeftCardExit(Object dataObject) {
Toast.makeToast(getApplicationContext(), "Left", Toast.LENGTH_SHORT).show();
}
On the first one i get the issue
"Can not resolve method 'makeToast.(android.Content.Context,
java.lang.String, int)' "
On the second one a similiar but just more specific pointer to my java file for the context
"Can not resolve method
'makeToast.(com.sanruza.alpak.tinderlike.MainActivity,
java.lang.String, int)' "
I understand that the correct syntax is .makeToast( context, String, int ), but i still can't get it to work.
It should be makeText instead of makeToast
Toast.makeText(context,toastMsg, Toast.LENGTH_SHORT).show();
See the docs for more info..
Please read the Google Developers link: Developers Toast Document
This snapshot should clarify your concern:
makeToast does not exist, you must use makeText.
Toast.makeText(getApplicationContext(), "Msg", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "Msg", Toast.LENGTH_LONG).show();
I have uploaded data onto parse.com and i am trying to retrieve the data from parse.com and display it in a textview.
i have a parseconstants class:
public static final String TYPE_STRING = "string";
public static final String KEY_FILE_TYPE = "fileType";
i send the message and it uploads to parse fine
String fileName = "text.txt";
String fileType = "text";
these 2 values are sent to parse.com as filename and filetype.
but when i get it back in inboxActivity here:
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
ParseObject message = mUserBio.get(position);
String messageType = message.getString(ParseConstants.KEY_FILE_TYPE);
ParseFile file = message.getParseFile(ParseConstants.KEY_FILE);
Uri fileUri = Uri.parse(file.getUrl());
if (messageType.equals(ParseConstants.TYPE_STRING)){
Intent intent = new Intent(getActivity(), ViewTextActivity.class);
intent.setData(fileUri);
startActivity(intent);
}
it does not call on the text activity class and does not show the class.
in the TextViewController i try to display the text into the TextView like below:
mDisplay = (TextView)findViewById(R.id.bioDisplay);
Uri textUri = getIntent().getData();
File string = new File(textUri.toString());
mDisplay.setText((CharSequence) string);
1) Why does the ViewtextActivity not show?
2) will the textview display the retrieved user bio?
Firstly, try to avoid calling constants like this:
ParseConstants.KEY_FILE_TYPE
Completely!
Rather import your class statically:
import static <your_package_name>.ParseConstants.*;
//now you can access your constants by calling it on its own:
String messageType = message.getString(KEY_FILE_TYPE);
EDIT
Your naming standards are not up to standard (An instance of File, should be called something to do with a File, and not "string")!! You are trying to display an object of type File within a TextView which won't work. Rather try this, instead of letting Android Studio cast it to a CharSequence:
mDisplay.setText(string.toString());
Thirdly, when calling ViewTextActivity, there are 3 ways to do this (as I am not sure if you are using a Fragment or not):
//if you are using a Fragment:
Intent intent = new Intent(getActivity(), ViewTextActivity.class);
//if you are using a FragmentActivity, you need to cast it:
Intent intent = new Intent((Your_Base_Activity) getActivity(), ViewTextActivity.class);
//if you are using a normal activity:
Intent intent = new Intent(Your_Activity_Name.this, ViewTextActivity.class);
As far as your TextView displaying data is concerned, your code does seem logically correct.
EDIT 2
From the ParseObject API, we see that getString will return the String value from that Key that is put in as the parameter (See Here).
According to you, you are checking if the return value is equal to the word "string". This doesn't make sense, as you are putting in the key value of "fileType".
My suggestion is check if the return is not null by using a log:
String messageType = message.getString(KEY_FILE_TYPE);
Log.e("MessageReturned: ", "Returned-" + messageType);
Or you can rethink, what the value that is supposed to equate to is supposed to be, as "string" doesn't make sense as far as I can see.
EDIT 3
Since you are saying that the value uploaded for the variable fileType is "text" should you not rather be doing this:
if (messageType.equals("text")){
EDIT 4
Your method of parsing information between the intents is obsolete. You need to try this:
if (messageType.equals(ParseConstants.TYPE_STRING)){
Intent intent = new Intent(getActivity(), ViewTextActivity.class);
intent.putExtra("fileUri", fileUri.toString());
startActivity(intent);
}
Then in your other class, you access it like so:
Bundle extras = getIntent().getExtras();
Uri receivedFileUri = Uri.parse(extras.getString("fileUri"));
I want to create a separate class within my application to handle error reporting and send specific errors to a database. However, I'm unable to figure out what the Context should be and how this should be properly coded. I assume it should still be possible, I just need to code it differently, if that is not the case, what is the best solution for me?
public class SendError implements Runnable
{
private String url;
public SendError(String errors, String form, String database, String SQL)
{
url = string;
Handler handler = new Handler();
handler.post(new Runnable() {
public void run() {
Toast toast = Toast.makeText(getContext, msg, Toast.LENGTH_LONG);
toast.show();
}
});
}
}
EDIT:
What I'm trying to do is create one class for my entire application that handles recording of SQL errors when submitting data to the database. The class needs to do 2 simple things. Submit information based on what form, database, time submitted, and the SQL code that created the error. The other thing I would like this class to do is to display a toast giving basic error information back to the user. I have the data submission portion of this worked out properly (hence the reason for the Runnable), but am still getting errors for the Toast.
Shouldn't do the work in your constructor, this makes your separate class useless.
public class SendError implements Runnable
{
private final Context context;
private final String url;
public SendError(Context context, String string) {
this.context = context;
this.url = string;
}
public void makeToast(String msg, String errors, String form, String database, String SQL) {
Handler handler = new Handler();
handler.post(new Runnable() {
public void run() {
Toast toast = Toast.makeText(context, msg, Toast.LENGTH_LONG);
toast.show();
}
});
}
}
Your context needs to be the relevant context, from using a Toast the Context is usually an Activity which can take the form of:
this (in an Activity)
ActivityName.this (in a inner class of an Activity)
getActivity (in a Fragment inside an Activity)
For example:
new SendError(YourActivity.this, "something").makeToast("Hello", "errors", "form", "database", "sql");
Just need to pass Context in the constructor when you create this class.
I would advise you rethink this class though - it's called "SendError" which sounds like a method name, it implements Runnable for some reason, and it's notifying the user with Toasts - sounds like too much for one class.
Toast toast = Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
or
Toast toast = Toast.makeText(SendError.this, msg, Toast.LENGTH_LONG).show();
I am making a service so I have service class which is extended from Service. I am getting a checkbox from PreferenceScreen and based on whether it is checked or not I perform an action. To get CheckBoxPreference I use getPreferenceManager() method. But it has red underline. When I hover over it shows me this error The method getPreferenceManager() is undefined for the type BatteryService. When I use the same code in my main class then it works. Here is my code
public int onStartCommand(Intent intent, int flags, int startId) {
initNotification();
final CheckBoxPreference checkboxPref = (CheckBoxPreference) getPreferenceManager().findPreference("cbAlarm");
checkboxPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference,
Object newValue) {
if (newValue.toString().equals("true")) {
Toast.makeText(getApplicationContext(), "Service Started", Toast.LENGTH_LONG).show();
registerReceiver(batteryInfoReceiver, new IntentFilter(
Intent.ACTION_BATTERY_CHANGED));
} else if (newValue.toString().equals("false")) {
stopService(new Intent(getBaseContext(),
BatteryService.class));
Toast.makeText(getApplicationContext(),
"Unchecked", Toast.LENGTH_SHORT).show();
}
return true;
}
});
return START_STICKY;
}
How can I solve this problem? Help Please
The getPreferencesManager() function is not available on Service derived objects - only on PreferenceActivity or PreferenceFragment derived objects where you likely copied the above code from, or individual Preference objects.
If you only wanted to sample the value of the checkbox preference when your service starts, use something like:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
boolean alarm = sp.getBoolean("cbAlarm", false); // defaulting to false
However, I'm guessing from your Listener code that you also want to be notified if the user changes the setting. That would mean keeping onPreferenceChange in the PreferenceActivity/PreferenceFragment, and sending the service a message. For that, consider something like Android best way to communicate from an Activity to a Service / Engine, or simply start/stop the whole service if it has nothing to do when the Alarm is off!
I'm trying to understand if the user has enabled the admin or not and LATER update a checkbox (in onResume).
The problem is that the activity which allows the user to enable the admin is launched and it's launched the following code without waiting for the user decision.
How could bypass it?
private void doAttivaRimuoviAdmin() {
if (isAdminAttivo()) {
mDPM.removeActiveAdmin(mDeviceAdminSample);
} else {
Intent localIntent = new Intent("android.app.action.ADD_DEVICE_ADMIN");
localIntent.putExtra("android.app.extra.DEVICE_ADMIN", mDeviceAdminSample);
localIntent.putExtra("android.app.extra.ADD_EXPLANATION",
getString(R.string.spiegazione_amministratore));
startActivityForResult(localIntent, 1);
// se non รจ stato dato il permesso, non attiva la checkbox
Editor e = mPrefs.edit();
if (isAdminAttivo()) {
e.putBoolean("spegnischermoabilitato", true);
} else {
e.putBoolean("spegnischermoabilitato", false);
}
e.commit();
Log.i(getString(R.string.app_name), ""+ mPrefs.getBoolean("spegnischermoabilitato", false));
}
}
In poor words, the sharedpreference "spegnischermoabilitato" always has FALSE within it.
From the documentation of startActivityForResult():
Launch an activity for which you would like a result when it finished.
When this activity exits, your onActivityResult() method will be
called with the given requestCode. Using a negative requestCode is the
same as calling startActivity(Intent) (the activity is not launched as
a sub-activity).
In other words, you will need to override onActivityResult(). In this method you will then have to check that the method is called with the requestCode you set in startActivityForResult(), and also that it contains the expected resultCode. If it does write your preference.