Syntax error on token "if", invalid AnnotationName - java

Hi I am working with android and I'm trying to put an "if" statement around this class but I get the error "Syntax error on token "if", invalid AnnotationName"
Any help?
private String str = "0";
if(str == 0){
public boolean onKeyDown(int keyCode, KeyEvent event)
{
//Handle the back button
if(keyCode == KeyEvent.KEYCODE_BACK)
{
//Ask the user if they want to quit
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Coupon")
.setMessage("Do you want a coupon texted to you?")
.setPositiveButton("YES!", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
//Stop the activity
Toast.makeText(buttonOne.this, "Great! You'll get one in just a couple of minutes.", Toast.LENGTH_LONG).show();
finish();
}
})
.setNegativeButton("Not now", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
//Stop the activity
finish();
}
})
.show();
return true;
}
else
{
return super.onKeyDown(keyCode, event);
}
}
}
else
{}

You can't put control structures (like if statements) outside a function.

you must use equals String method:
if (str.equals("0")){
...
}

Related

How to implement onKeyDown in Fragment

I change all my activitys to Fragment. I got stuck in the onkeydown part.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (!sector.getText().toString().equals("Sector") && (media.isChecked() || completa.isChecked())) {
siguiente.setEnabled(true);
} else {
siguiente.setEnabled(false);
}
return super.onKeyDown(keyCode, event);
}
You can do this by defining method in your fragment class. For example:
public void onMyKeyDown(int key, KeyEvent event){
//define your statement like
if (Integer.parseInt(android.os.Build.VERSION.SDK) > 5
&& key == KeyEvent.KEYCODE_BACK
&& event.getRepeatCount() == 0) {
new AlertDialog.Builder(this)
.setTitle("Title")
.setMessage("Do you really want to Exit?")
.setIcon(R.drawable.logo)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
finish();
}})
.setNegativeButton(android.R.string.no, null).show();
}
}
Call onMyKeyDown method whenever a key-down event is raised in your Activity class. example:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
//call fragment method onMyKeyDown(keyCode, event)
return super.onKeyDown(keyCode, event);
}

Detect Back Button Event when Dialog is Open

I'm building an app that has 2 dialogues that open up and I want something to occur if the user presses the back button while certain dialogues are open. However, for some reason, the back button event is not registering when the dialogues are open. I tested it by putting a log in onBackPressed() and whenever the dialogues are NOT open and I'm simply on the main activity, the logs appear on logcat. However, if the dialogues are open, I simply get this:
W/InputEventReceiver: Attempted to finish an input event but the input event receiver has already been disposed.
Below I have placed the code for the dialogues:
public void pair() {
final Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
AlertDialog.Builder pairedList = new AlertDialog.Builder(this);
pairedList.setTitle("Paired Devices");
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.select_dialog_singlechoice);
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
arrayAdapter.add(device.getName());
}
}
pairedList.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mBluetoothAdapter.disable();
// pair_dialog = false;
}
});
pairedList.setPositiveButton("Pair New", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivityForResult(new Intent(android.provider.Settings.ACTION_BLUETOOTH_SETTINGS), 0);
}
});
pairedList.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// connect_dialog = true;
String strName = arrayAdapter.getItem(which);
AlertDialog.Builder builderInner = new AlertDialog.Builder(MainActivity.this);
builderInner.setMessage(strName);
builderInner.setTitle("Connect To:");
builderInner.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
for (BluetoothDevice device : pairedDevices) {
if(device.getName().equals(strName)){
paired = device;
dialog.dismiss();
}
}
}
});
builderInner.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// connect_dialog = false;
pairedList.show();
}
});
builderInner.show();
}
});
pairedList.show();
// pair_dialog = true;
}
Below is my onBackPressed() method which is right after the above method. Nothing out of the ordinary, I don't think.
#Override
public void onBackPressed() {
Log.e(TAG, "Back Button Pressed");
super.onBackPressed();
}
Like I said, if the dialogues are not open, the log shows up just fine in logcat but if the dialogues are open, it's like the back button doesn't register.
this worked for me...
yuordialog.setOnKeyListener(new Dialog.OnKeyListener() {
#Override
public boolean onKey(DialogInterface arg0, int keyCode,
KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
//your stuff....
}
return true;
}
});
If you have added,
dialog.setCancelable(false);
change it to,
dialog.setCancelable(true);
Actually, setCancelable(false) cancel the event of touch outside the dialog and back press also.
You can also use
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialogInterface) {
//your dismiss code here
}
});
This listens to both backpress events and dismiss by touch.

Android Passing a variable with a dialog box which gets bypassed in OnCreate

If you read the code you can see that I've placed a Toast message after the dialog box. I want it to made so the "First" variable which is declared as public inside the same class gets its value by going through the process of the dialog box eventually getting to the if-statement and finally displaying the Toast message inside the if-statement.
Initially I had a method called "showDialogHOME" where all of the following code was being passed.
I thought I try it this way with the hope of solving the problem.
This code is located in OnCreate()
final CharSequence[] items = {"X", "O"};
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setCancelable(false);
alertDialog.setTitle("Who goes first?");
alertDialog.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item] == "X") {
First = 1;
Toast.makeText(getApplication(), "Computer goes first.", Toast.LENGTH_SHORT).show();
} else if (items[item] == "O") {
First = 2;
if (First == 2) {
Toast.makeText(getApplication(), "2 WORKS", Toast.LENGTH_SHORT).show();
}
}
dialog.dismiss();
}
});
alertDialog.show();
if (First == 1){
Toast.makeText(getApplication(), "Inside If", Toast.LENGTH_SHORT).show();
}
Toast.makeText(getApplication(), "After If Message", Toast.LENGTH_SHORT).show();
The problem is that the lines after you create and display the AlertDialog, don't wait and executes before you set the value.
You probably want to use an event for that:
alertDialog.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
if (First == 1){
Toast.makeText(getApplication(), "Inside If", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplication(), "After If Message", Toast.LENGTH_SHORT).show();
}
});
EDIT
You can also try this:
alertDialog.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item] == "X") {
First = 1;
//Toast.makeText(getApplication(), "Computer goes first.", Toast.LENGTH_SHORT).show();
} else if (items[item] == "O") {
First = 2;
if (First == 2) {
// Toast.makeText(getApplication(), "2 WORKS", Toast.LENGTH_SHORT).show();
}
}
dialog.dismiss();
if (First == 1) {
Toast.makeText(getApplication(), "Inside If", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplication(), "After If Message", Toast.LENGTH_SHORT).show();
}
}
});
alertDialog.show();

Back button press twice before quitting app

How can I configure the back button to be pressed twice before the app exits? I want to trigger
#Override
public void onBackPressed() {
//custom actions
//display toast "press again to quit app"
super.onBackPressed();
}
Try this:
private boolean doubleBackToExitPressedOnce = false;
#Override
protected void onResume() {
super.onResume();
// .... other stuff in my onResume ....
this.doubleBackToExitPressedOnce = false;
}
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Press twice to exit", Toast.LENGTH_SHORT).show();
}
This snippet handle also the reset state when the activityis resumed
I see this question is a bit old but I though this might help some people looking for an alternative to the answers already given.
This is how I handle backing out of my applications. If someone has a better -- or a Google suggested -- method of accomplishing this I'd like to know.
Edit -- Forgot to mention this is for Android 2.0 and up. For previous versions override onKeyDown(int keyCode, KeyEvent event) and check for keyCode == KeyEvent.KEYCODE_BACK. Here is a good link to check out.
private boolean mIsBackEligible = false;
#Override
public void onBackPressed() {
if (mIsBackEligible) {
super.onBackPressed();
} else {
mIsBackEligible = true;
new Runnable() {
// Spin up new runnable to reset the mIsBackEnabled var after 3 seconds
#Override
public void run() {
CountDownTimer cdt = new CountDownTimer(3000, 3000) {
#Override
public void onTick(long millisUntilFinished) {
// I don't want to do anything onTick
}
#Override
public void onFinish() {
mIsBackEligible = false;
}
}.start();
}
}.run(); // End Runnable()
Toast.makeText(this.getApplicationContext(),
"Press back once more to exit", Toast.LENGTH_SHORT).show();
}
}
You could do what you're asking with a global integer and just count it, if > 2, quit.
But you could take a better (IMO) approach, where you question the user if they would like to quit or not:
private void questionQuit(){
final CharSequence[] items = {"Yes, quit now", "No, cancel and go back"};
builder = new AlertDialog.Builder(mContext);
builder.setCancelable(false);
builder.setTitle("Are you sure you want to quit?");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
switch(item){
case 0:
quit();
break;
case 1:
default:
break;
}
}
}).show();
AlertDialog alert = builder.create();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK :
int i = 0 ;
if(i == 1 )
{
finish();
}
i++;
return true;
}
}
return super.onKeyDown(keyCode, event);
}

Scope Variable issue for onKeyDown event

I am having trouble using the var "str" in an if statement. I know that it is a scope problem but I am not sure how to fix it. I have failed several times.
My goal is to use the value of "str" in an if statement to show an alert or not.
Restriction is I have to assign the value of "str" this way only.
public class MyJavaScriptInterface
{
public String showHTML(String html)
{
String str = html;
return str;
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
//Handle the back button
if(keyCode == KeyEvent.KEYCODE_BACK && str =="0")
{
//Ask the user if they want to quit
Update:
OK I was try not to bother you with reading the whole code but it's short and it might help.
In a webview I show the html page and I also read a hidden variable which will decide if an alert box should show or not. I am just trying to get that value to the if statement in the keydown push. Here is the whole code.
package com.ishop.pizzaoven;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class buttonOne extends Activity
{
WebView wb = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.buttons);
wb = new WebView(this);
wb.getSettings().setJavaScriptEnabled(true);
wb.setWebViewClient(new HelloWebViewClient());
wb.getSettings().setJavaScriptEnabled(true);
wb.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");
/* WebViewClient must be set BEFORE calling loadUrl! */
wb.setWebViewClient(new WebViewClient()
{
#Override
public void onPageFinished(WebView view, String url)
{
/* This call inject JavaScript into the page which just finished loading. */
wb.loadUrl("javascript:window.HTMLOUT.showHTML(document.getElementById('sendtextcoupon').value);");
}
});
wb.loadUrl("http://ishopstark.com/mobileapp.php?category=1");
setContentView(wb);
}
private class HelloWebViewClient extends WebViewClient
{
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true;
}
}
final Context myApp = this;
public class MyJavaScriptInterface
{
public void showHTML(String html)
{
String str = html;
}
}
public boolean onKeyDown(int keyCode, KeyEvent event)
{
//Handle the back button
if(keyCode == KeyEvent.KEYCODE_BACK)
{
//Ask the user if they want to quit
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Coupon")
.setMessage("Do you want a coupon texted to you?")
.setPositiveButton("YES!", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
//Stop the activity
Toast.makeText(buttonOne.this, "Great! You'll get one in just a couple of minutes.", Toast.LENGTH_LONG).show();
finish();
}
})
.setNegativeButton("Not now", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
//Stop the activity
finish();
}
})
.show();
return true;
}
else
{
return super.onKeyDown(keyCode, event);
}
}
}// End of main class
Update 2:
ok so i changed my code a bit. But now I get alert errors any ideas? "The method setIcon(int) is undefined for the type buttonOne.MyJavaScriptInterface" I get this error on .setIcon(android.R.drawable.ic_dialog_alert) and return super.onKeyDown(keyCode, event);
public class MyJavaScriptInterface
{
public String showHTML(String html)
{
String str = html;
return str;
}
public boolean onKeyDown(int keyCode, KeyEvent event, String str)
{
//Handle the back button
if(keyCode == KeyEvent.KEYCODE_BACK && str == "0")
{
//Ask the user if they want to quit
AlertDialog.Builder alertbox = new AlertDialog.Builder(buttonOne.this);
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Coupon")
.setMessage("Do you want a coupon texted to you?")
.setPositiveButton("YES!", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
//Stop the activity
Toast.makeText(buttonOne.this, "Great! You'll get one in just a couple of minutes.", Toast.LENGTH_LONG).show();
finish();
}
})
.setNegativeButton("Not now", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
//Stop the activity
finish();
}
})
.show();
return true;
}
else
{
return super.onKeyDown(keyCode, event);
}
}
}
Not sure exactly what your aim is, but can you not make the string a member variable?
public class MyJavaScriptInterface
{
private String str;
public String showHTML(String html)
{
str = html;
return str;
}
}
It would be helpful to know which class the listener method is in; you have it outside the MyJavaScriptInterface class, but don't have any context around it. So when onKeyDown happens, do you have the html in order to run the showHTML(html) method? Has it already been run? Do you have an instance of MyJavaScriptInterface to run it on?
If you have an extra } in there and it is indeed a part of the same class, then I would agree with #Steve's answer.
If it's outside the class, then there are many solutions depending upon your actual situation. The simplest way would be to make str an instance variable as #Steve said, and then add an accessor method:
public String getStr(){
return str;
}
and then have your listener call that accessor instead of attempting to use str directly:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
// Get an instance of MyJavaScriptInterface;
MyJavaScriptInterface mjsi = new MyJavaScriptInterface();
//Handle the back button
if( keyCode == KeyEvent.KEYCODE_BACK && mjsi.getStr().equals("0") )
{
//Ask the user if they want to quit

Categories