How do I use Toast notification properly on android? - android

I can't seem to be able to use the toast notification properly. In all of my other apps it worked great but in this one it doesn't. In this app I started using openGL with a framework from a book named "Beginning Android Games" and now I don't seem to be able to use the toast notification. I have no idea what to do... It fails because of the context. How can I make a context that will work? Please help me! this is part of my code because the code is too long:
private void updateReady() {
Coin.number = 0;
if (game.getInput().getTouchEvents().size() > 0) {
state = GAME_RUNNING;
Coin.number = 0;
Num.number = 0;
Toast.makeText(this, "Start!", Toast.LENGTH_SHORT).show();
}
}
When I put the line:
Toast.makeText(this, "Start!", Toast.LENGTH_SHORT).show();
in the class that extends Activity and run it it just doesn't do anything... I tried to make it into a method and call it from other classes but it got a force close...

You can try using getApplicationContext() to get a reference to the current Activity context

You could always make your application context, or the context of whatever activity you're starting your GameScreen from, available statically or by passing it as an argument from whatever creates your instance.
Having said that, though, beware of memory leaks!

Maybe this helps.
I had class defined like this
public class tutorialThree extends Activity implements View.OnClickListener
I tried to use Toast like this
Toast.makeText(this, "Wallpaper set", Toast.LENGTH_SHORT).show();
Did not work, because my class implements that interface "View.OnClickListener" (or whatever it is :))
So toast gets confused with "this" reference, you have to be more precise, so add name of your class before "this" keyword, like this:
Toast.makeText(tutorialThree.this, "Wallpaper set", Toast.LENGTH_SHORT).show();
This solved my problem, now i can see toast.

I assume you're working with this framework called "Beginning Android Games 2".
According to this code, the instance variable you need here is glGame, which is a GLGame object. It extends Activity, so you can just do this:
Toast.makeText(glGame, "Start!", Toast.LENGTH_SHORT).show();

Related

Creating a toast in android and specifying the location

I am working on my first Android app and I am trying to create a toast and specify the location where I want it to appear. When I was using the code that is now commented (it didn't customize the toast's location) the app ran perfectly on the emulator, but now that I am trying to customize the location and using the code below the comments, the app stops running when I click in the UI on the button meant to show the toast.
Do you have any idea of why this is happening? Because I have seen very similar codes (almost the same) presented as correct, so this should be working. I know this is a very simple code and a simple question, but still, I cannot figure out what is wrong with my code.
This is the code on my onButtonClick:
public void onClick(View V) {
// Toast.makeText(QuizActivity.this,
// R.string.correct_toast,
// Toast.LENGTH_SHORT).show();
Toast t = new Toast(QuizActivity.this);
t.setText(R.string.correct_toast);
t.setDuration(Toast.LENGTH_SHORT);
t.setGravity(Gravity.TOP|Gravity.LEFT,0,0);
t.show();
}
From https://developer.android.com/reference/android/widget/Toast#Toast(android.content.Context) :
Construct an empty Toast object. You must call setView(View) before you can call show().
Your code crashes because now you are using the Toast() constructor. And you need to setView(View) before show(). While this is not necessary with makeText().
As I understand, makeText() creates a View for you setting the text from the second parameter. But the constructor doesn't, and the setText() method does not either. setText() only update the an existing text:
From https://developer.android.com/reference/android/widget/Toast#setText(int) :
Update the text in a Toast that was previously created using one of the makeText() methods.
Here is an example of how to do that:
Custom toast on Android: a simple example
Edit
In any case, you can create the Toast with your initial code, without calling show().
public void onClick(View V) {
Toast t = Toast.makeText(QuizActivity.this,
R.string.correct_toast,
Toast.LENGTH_SHORT);
t.setGravity(Gravity.TOP|Gravity.LEFT,0,0);
t.show();
}
Edit 2
Now you have edited your code, but you are passing the Button View.

Getting access to globals in DialogFragment static class

I've followed Google docs and created an inner class to popup a dialog in my android app.
I've been running it fine in eclipse for a while, unbeknownst to me there was an error that came up when I imported the app into android studio to start using the stable release. I was getting the "Fragment inner class should be static" error upon trying to build.
OK so I understand now after researching that this is a bad thing, but when I change it to static, I now have a bunch of references to (a) global variables , and (b) "MainActivity.class" , that are now errors.
So inside this DialogFragment inner class, how do I access my globals, or pass them in, and how do I reference MainActivity.class ?
Eg:
final EditText input = new EditText(MainActivity.this);
for (NewsEvent ne : filteredList) { //filteredList is global List of objects
...
I am calling the dialog in the onOptionsItemSelected like this:
AlertDialogFragment alert = new AlertDialogFragment();
alert.show(this.getFragmentManager(), "Alerts");
To send a Data to the DialogFragment use static newInstance(params) method.
Put the Data in a Intent and on the onCreate() method get your Data from the Intent.
Check this example from the Android dev

Android Toast Accumulation Testing

Like many others, i've been trying to solve the problem of toast accumulation.
How to prevent Multiple Toast Overlaps
toast issue in android
Cancelling an already open toast in Android
Best way to avoid Toast accumulation in Android
I finally decided to keep track of the current displayed toast and cancel it when another arrives (there's some more logic involved), but i could have use only one toast and change it message. What i want to know is this... Is there a way to TEST this behaviour? Im currently using Robotium and tried different things, but unfortunately the methods to check for toasts (solo.waitForText and solo.searchForText) aren't helping me as i can't make something like
assertTrue(solo.waitForText(text));
//maybe even some sleep here
assertFalse(solo.searchText(text);
Has anyone done something like this? Is there a way to test this using Robotium? using somethig else?
You can use a robotium condition to wait for the text to disappear. Here's a method I use for that.
private void waitForTextToDisappear(final String text, int wait) {
Condition textNotFound = new Condition() {
#Override
public boolean isSatisfied() {
return !solo.searchText(text);
}
};
assertTrue("Text gone: " + text, solo.waitForCondition(textNotFound, wait));
}

In android, why getCurrentInputEditorInfo() = null?

When clicking a flowWindow button, the application starts a Service extends InputMethodService as follow:
public void onStart(Intent intent, int a)
{
super.onStart(intent , a);
EditorInfo ed=getCurrentInputEditorInfo();
}
The question is, no matter what the current activity(from other application) is, the "ed" equals "null", of course the following codes such as "Log.d("tag",ed.hintText+"")" makes an error.
Is the grammar incorrect, or the application lacks some permission?
Because the EditorInfo doesn't exist until you're connected to a text editor. This doesn't happen in onStart, it happens in onStartInput. Where its also passed as a parameter, making this function a bit unnecessary.

Android: How can I print a variable on eclipse console?

I wanted to print the value of a variable on the console for my debugging purpose, but System.out.println doesn't work.
System.out.println and Log.d both go to LogCat, not the Console.
Window->Show View->Other…->Android->LogCat
I'm new to Android development and I do this:
1) Create a class:
import android.util.Log;
public final class Debug{
private Debug (){}
public static void out (Object msg){
Log.i ("info", msg.toString ());
}
}
When you finish the project delete the class.
2) To print a message to the LogCat write:
Debug.out ("something");
3) Create a filter in the LogCat and write "info" in the input "by Log Tag". All your messages will be written here. :)
Tip: Create another filter to filter all errors to debug easily.
Writing the followin code to print anything on LogCat works perfectly fine!!
int score=0;
score++;
System.out.println(score);
prints score on LogCat.Try this
I think the toast maybe a good method to show the value of a variable!
Ok, Toast is no complex but it need a context object to work, it could be MyActivity.this, then you can write:
Toast.maketext(MyActivity.this, "Toast text to show", Toast.LENGTH_SHORT).show();
Although Toast is a UI resource, then using it in another thread different to ui thread, will send an error or simply not work
If you want to print a variable, put the variable name.toString() and concat that with text you want in the maketext String parameter ;)
toast is a bad idea, it's far too "complex" to print the value of a variable. use log or s.o.p, and as drawnonward already said, their output goes to logcat. it only makes sense if you want to expose this information to the end-user...
If the code you're testing is relatively simple then you can just create a regular Java project in the Package Explorer and copy the code across, run it and fix it there, then copy it back into your Android project.
The fact that System.out is redirected is pretty annoying for quickly testing simple methods, but that's the easiest solution I've found, rather than having to run the device emulator just to see if a regular expression works.
By the way, in case you dont know what is the exact location of your JSONObject inside your JSONArray i suggest using the following code: (I assumed that "jsonArray" is your main variable with all the data, and i'm searching the exact object inside the array with equals function)
JSONArray list = new JSONArray();
if (jsonArray != null){
int len = jsonArray.length();
for (int i=0;i<len;i++)
{
boolean flag;
try {
flag = jsonArray.get(i).toString().equals(obj.toString());
//Excluding the item at position
if (!flag)
{
list.put(jsonArray.get(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
jsonArray = list;

Categories

Resources