Scope Variable issue for onKeyDown event - java

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

Related

Remember checkbox within a dialog

I try to remember the checkbox within a dialogue but in comparison remember == false the variable remember still has not changed its value. In the loop is iterated as many times as the size of lelements_tmp before call showDialogSameFile() so neither can I use the variable remember within the loop. How can I do it? Thanks in advance.
private boolean remember = false;
// in the program
// add files to List lelements_tmp
while (i < lelements_tmp.size()) {
File fto = new File(lelements_tmp.get(i).getFile());
String to = null;
try {
to = fto.getCanonicalPath();
} catch (IOException e) {
e.printStackTrace();
}
if (fto.exists()) {
showDialogSameFile(fto, to, i);
i++;
continue;
}
thread(i);
i++;
}
private void showDialogSameFile(File f, String to, final int i) {
TextView title = null;
if (f.isDirectory())
title = this.getTitle("The directory " + to + " already exists. Do you want to replace the contents?");
else if (f.isFile())
title = this.getTitle("The file " + to + " already exists. Do you want to replace it?");
String[] item = {"Apply to all"};
AlertDialog ad = new AlertDialog.Builder(context)
.setCustomTitle(title)
.setMultiChoiceItems(item, null,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int indexSelected, boolean isChecked) {
if (isChecked)
remember = true;
}
})
.setPositiveButton("Aceptar",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
thread(i);
}
})
.setNegativeButton("Cancelar",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
})
.create();
if (remember == false)
ad.show();
}
I've had to refactor the code a bit, but basically with this work. It's necessary to call to the method from non-UI thread. Based on this response https://stackoverflow.com/a/11369224/5089855
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import java.util.concurrent.Semaphore;
public class Proof {
private Semaphore mutex = new Semaphore(0, true);
private boolean remember = false;
private Activity context;
public Proof(Activity context) {
this.context = context;
}
private boolean showDialogMismoArchivo() {
context.runOnUiThread(new Runnable() {
public void run() {
String[] item = {"Apply all"};
AlertDialog ad = new AlertDialog.Builder(context)
.setTitle("¿Reemplazar?")
.setMultiChoiceItems(item, null,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int indexSelected, boolean isChecked) {
if (isChecked)
remember = true;
else
remember = false;
}
})
.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mutex.release();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mutex.release();
}
})
.create();
ad.show();
}
});
try {
mutex.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
return remember;
}
}

Android: Simplest Internet connection dialog with Retry/Cancel

I am stuck in implementing a dialog which checks for internet connectivity as soon as the app is opened (i.e. in onCreate()). However, I moved the dialog code to a different class to keep the MainActivity clean.
I need to check for connectivity everytime the user clicks retry, show the dialog again if internet is not present else call the onRefresh() method present in the MainActivity class.
The code looks something like this:
public static boolean showNoConnectionDialog(final Context c) {
if(checkConnectivity(c))
{
result = true;
return result;
}
else
{
AlertDialog.Builder b =new AlertDialog.Builder(c);
b.setTitle("No Connection");
b.setMessage("Cannot connect to the internet!");
b.setPositiveButton("Retry", new AlertDialog.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(!checkConnectivity(c))
showNoConnectionDialog(c);
else
{
result = true;
}
}
});
b.setNegativeButton("Exit", new AlertDialog.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((Activity)c).finish();
}
});
b.create().show();
}
return result;
}
private static Boolean checkConnectivity(Context c) {
ConnectivityManager cm = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
// test for internet connection
if (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isAvailable() && cm.getActiveNetworkInfo().isConnected())
return true;
else
return false;
}
In the MainActivity, I tried:
if(DialogBoxes.showNoConnectionDialog(this)){
onRefresh();
}
However, clicking the Retry button after connecting to the internet does nothing, since the "if" part is checked only once. Using while instead of if causes the UI to stop responding.
What do I do ?
First declare your AlertDialog outside of any method but inside of your class:
AlertDialog dialog;
Then inside of your positive button listener:
b.setPositiveButton("Retry", new AlertDialog.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(!checkConnectivity(c))
dialog.show();
else
{
result = true;
}
}
});
dialog = b.create();
dialog.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);
}

PostDialogListener() android Facebook api issue

I am trying to create a small app that posts the entries made by an user in my app to facebook when they press the back button to quit. I already have SSO and everything else set up, the problem is it does not recognize PostDialogListener as a valid listener. Says does not exist, the code where I am trying to use it
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
Log.d(this.getClass().getName(), "back button pressed");
fb.dialog(getApplicationContext(), "stream.publish", new PostDialogListener());
Toast t=Toast.makeText(getApplicationContext(), " Back pressed ", Toast.LENGTH_LONG);
t.show();
}
return super.onKeyDown(keyCode, event);
}
I tried putting the dialog code in other places too, but same result, PostDialogListener is not being recognized.
You probably don't import it from example. Add these classes to your project:
public abstract class BaseDialogListener implements DialogListener {
#Override
public void onFacebookError(FacebookError e) {
e.printStackTrace();
}
#Override
public void onError(DialogError e) {
e.printStackTrace();
}
#Override
public void onCancel() {
}
}
public class PostDialogListener extends BaseDialogListener {
#Override
public void onComplete(Bundle values) {
final String postId = values.getString("post_id");
if (postId != null) {
showToast("Message posted on the wall.");
} else {
showToast("No message posted on the wall.");
}
}
}

Syntax error on token "if", invalid AnnotationName

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")){
...
}

Categories