Good Day, So I have this program where the user will scan a QR code and get the value of it in the SQLite database but before I get the value the dialog box pops-up messaging me that "there is no participant found". Below is my code:
This is my onStart override.
#Override
protected void onStart()
{
super.onStart();
getparticipantid = tvParticipantID.getText().toString();
etparticipantidvalue.setText(getparticipantid);
getParticipantIbeam();
}
This is my activity where it will load the data from the database once the user scans the QR code.
private void getParticipantIbeam()
{
SQLiteFunctionUlitity.GameIBeamParticipant memberInfo = SQLiteFunctionUlitity.getparticipantIbeam(getparticipantid, mDbHelper.getSqliteObjectWithReadable());
if (memberInfo != null)
{
tvParticipantName.setText(memberInfo.getParticipantName());
tvParticipantNation.setText(memberInfo.getParticipant_nationality());
tvParticipantCategory.setText(memberInfo.getCategory());
tvWave.setText(memberInfo.getWave_number());
tvCategory.setText(memberInfo.getCategory());
}
else
{
Context context = this;
AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
builder1.setMessage("No Participant found in the Game.");
builder1.setCancelable(true);
builder1.setPositiveButton("Scan Again", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
Intent intent = new Intent(GameiBeamLineTracing.this, ScanGameIbeam.class);
startActivity(intent);
finish();
}
});
builder1.setNegativeButton("Close", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
onStop();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}
}
As you can see I call the getParticipantIbeam activity in onStart method but when I call it, it reads the else statement rather than the if statement.
I know this is a simple if else statement and lifecycle but I am desperate to know the answer.
I have used the library for scanning QR code, its very simple it may help you.
QR Code implementation library for android, Click here (blikoon)
Definitely this library will solve your all QR Code related issue and dont forget to implement run time permissions like photo , gallery etc.
Related
I have a language setting in my android app. I save the current language into SharedPreferences and I have a onSharedPreferencesChanged that restarts all activites in the stack so they can be shown in the correct language.
This works like a charm but the language setting is being shown into a Dialog, so when I click on the language I want to change it to, shared preferences changes and then I get a Leaked Window error.
public void showDialog(View v) {
final CharSequence[] items = { res.getString(R.string.english),
res.getString(R.string.spanish) };
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(res.getString(R.string.change_language));
builder.setSingleChoiceItems(items, selected,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
switch (item) {
case 0: // English
if (selected == 0) {
Toast.makeText(
SettingsActivity.this,
res.getString(R.string.current_language),
Toast.LENGTH_LONG).show();
break;
}
changeLocale("en");
break;
case 1: // Spanish
if (selected == 1) {
Toast.makeText(
SettingsActivity.this,
res.getString(R.string.current_language),
Toast.LENGTH_LONG).show();
break;
}
changeLocale("es");
break;
}
alert.dismiss();
}
});
alert = builder.create();
builder.show();
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if (key.equals("language")) {
restartActivity();
}
}
This method is in the parent activity of all of my activities:
public void restartActivity() {
Intent intent = getIntent();
finish();
startActivity(intent);
}
Im getting a leaked window in the line builder.show() because I'm restarting all the activities when the shared preferences change. How can I show the dialog and restart my activities without getting this error?
Thanks in advance
Explaining Abdallah's answer try to move dismiss() up as the first statement in your onClick callback method.
EDIT: First of all after you call alert = builder.create(); you should call alert.show() and not builder.show(). Furthermore having the modifications mentioned in comments you should not receive the error no more.
Your code is trying to show a Dialog after exiting the Activity.
To prevent this, you should dismiss() your Dialog before restarting Activities.
I've managed to successfully implement Facebook login into my Android app.The issue I'm facing is,on my logout,whenever I click the logout button,I would like to capture the click of "Cancel / Logout" options.How do I go about doing this?Below are images attached for a much clearer illustration.
As shown in the images,how do I go about capturing the clicks in the highlighted red circles?
Below attached are my codes for the login/logout activity as well.Thank you :)
View view = inflater.inflate(R.layout.splash, container, false);
LoginButton authButton = (LoginButton) view
.findViewById(R.id.login_button);
authButton.setFragment(this);
// Get more permissions
authButton.setPublishPermissions(Arrays
.asList("publish_actions,read_stream"));
authButton.setFragment(getParentFragment());
I now this post is very old but...
I had the same problem as you, what I did was:
(only sure for facebook sdk v2.0)
1. Go to package com.facebook.widget;
2. Open the file LoginButton.java;
3. Go to line 819 inside the public void onClick(View v);
4. See the allert Dialog? I just comented the code as follows:
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(message)
.setCancelable(true)
.setPositiveButton(logout, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
openSession.closeAndClearTokenInformation();
}
});
/*.setNegativeButton(cancel, null);*/
builder.create().show();
And it is done!, no more annoying cancel button on dialog.
(You can also remove the whole dialog)
I got the same problem and searched some many answers,but they doesnot work,so I just write some new codes in LoginButton.java in facebook sdk,my frist step:
public interface LogoutListener{
public void afterLogin();
}
private LogoutListener mLoginoutListener;
public void setLogoutListener(LogoutListener loginoutListener){
this.mLoginoutListener = loginoutListener;
}
second step:find 811 lines in LoginButton.java and you will see the code just like this:
private class LoginClickListener implements OnClickListener {
#Override
public void onClick(View v) {
Context context = getContext();
final Session openSession = sessionTracker.getOpenSession();
if (openSession != null) {
// If the Session is currently open, it must mean we need to log out
if (confirmLogout) {
// Create a confirmation dialog
String logout = getResources().getString(R.string.com_facebook_loginview_log_out_action);
String cancel = getResources().getString(R.string.com_facebook_loginview_cancel_action);
String message;
if (user != null && user.getName() != null) {
message = String.format(getResources().getString(R.string.com_facebook_loginview_logged_in_as), user.getName());
} else {
message = getResources().getString(R.string.com_facebook_loginview_logged_in_using_facebook);
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(message)
.setCancelable(true)
.setPositiveButton(logout, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
openSession.closeAndClearTokenInformation();
// here is what I added
if(mLoginoutListener != null){
mLoginoutListener.afterLogin();
}
}
})
.setNegativeButton(cancel, null);
builder.create().show();
} else {
openSession.closeAndClearTokenInformation();
}
third step,and this is how I use :
LoginButton floginButton = (LoginButton)findViewById(R.id.flogin_button);
floginButton.setLogoutListener(new LogoutListener() {
#Override
public void afterLogin() {
// do what you want ,when user click the "OK" button.
}
});
I changed a little bit codes in facebook sdk,and it worked for me,I hope this can help you.
In my app i have a function that checks the entered text from a displayed AlertDialog with an input text. If the text is equal to a string variable, return True, else return False, and catch this resulting value to continue conditional code.
But it seems its a little difficult to do this as i've read in other posts asking how to solve the same problem.
I've already done this:
private boolean checkAdministratorPassword() {
final enterPasswordResult[0] = false;
AlertDialog.Builder alert = new AlertDialog.Builder(mContext);
alert.setTitle("Confirm action");
alert.setIcon(R.drawable.ic_launcher);
alert.setMessage("Enter administrator pass to continue");
final EditText input = new EditText(mContext);
input.setPadding(5, 0, 5, 0);
alert.setView(input);
alert.setPositiveButton("Accept", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String strPass = input.getEditableText().toString();
if (strPass.length() == 0) {
dialog.cancel();
}
if (strPass.equalsIgnoreCase(Constantes.ADMIN_PASS)) {
enterPasswordResult[0] = true;
dialog.cancel();
} else {
Toast.makeText(mContext, "Invalid pass..!!", Toast.LENGTH_LONG).show();
dialog.cancel();
}
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
AlertDialog alertDialog = alert.create();
alertDialog.show();
return enterPasswordResult[0];
}
And i call the function this way:
If ( checkAdministratorPassword() == True ){
//true conditions
}
But the problem is that the check function doesnt wait for the result to continue with the code, it just continue by itself and i dont get the appropiate behavior.
The issue is you're trying to handle an async event in the logcal flow of your program. You can do this if you make the Dialog it's own class and use an Interface to callback to your host activity. Check out the documentation on DialogFragment.
public interface PasswordCheckListener{
public void valid(boolean check);
}
private static class PasswordDialog extends DialogFragment {
private PasswordCheckListener listener;
public static PaswordDialog newInstance(PasswordCheckListener listener){
this.listener = listener;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
//Put your dialog creation code here
}
private checkAdminPassword(){
//Whatever your check passowrd code is
listener.valid(result);
}
}
I realize I didn't implement all the code for you but that's the general idea. By using an interface you can call back to your host Activity or Fragment when the user enters the password and presses submit. You can then handle the event as it happens, rather than having to deal with it in your program flow.
Thank you all for your answers!! i've found the right way to achieve this problem by creating an Activity whith theme "Theme.Dialog", an input text and two buttons (Accept, Cancel), i start this activity for result asking the user to enter the administrator pass to continue, checking the string and then returning again to onActivityResult() from previous activity with the correct information to proceed.
The title might not be very clear, its kind of hard to explain in a short title. But here is the problem.
I have an activity, MainActivity which then shows an activity at start to show FragmentA. In MainActivity there is a menu that is shown which is accessible via FragmentA. From the menu in FragmentA the user clicks on Generate Password which then calls another activity called GeneratePassword called using startActivityForResult. When the user presses the submit button the user is then sent back to FragmentA and the function onActivityResult within the MainActivity. Within this function, I then make use of a common class which allows me to show an AlertDialog with Yes and No Buttons. OnActivityResult works fine if I take out the common.showYesNoDialog() if statement, but when this is being used I get an exception
android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
Below is the code that starts the GeneratePassword Activity
Intent generatePasswrodIntent = new Intent(mMainActivity, GeneratePassword.class);
startActivityForResult(generatePasswrodIntent, AddNewLogin.GENERATE_PASSWORD);
return(true);
Below is the code that sets the result from the GeneratePassword activity
Intent intent = new Intent();
Bundle bundle = new Bundle();
bundle.putString("password", generatePassword.generatePassword());
intent.putExtras(bundle);
setResult(AddNewLogin.GENERATE_PASSWORD, intent);
finish();
Below is the code from the onActivityResult that shows the alert dialog
Bundle bundle = data.getExtras();
String password = bundle.getString("password");
Log.d("PASSWORD", password);
if (common.showYesNoDialog("Your Generated Password Is:\n " + password + "\nDo you want to copy this to the clipboard?", false))
{
ClipboardManager clipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
clipboard.setText(password);
}
Below is the YesNoDialog function, but I know this works fine as I have used it in several places within my app without problem.
final Handler handler = new Handler()
{
#Override
public void handleMessage(Message mesg)
{
throw new RuntimeException();
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setCancelable(isCancelable);
builder.setMessage(message)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialogResult = true;
handler.sendMessage(handler.obtainMessage());
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialogResult = false;
handler.sendMessage(handler.obtainMessage());
}
});
AlertDialog alert = builder.create();
alert.show();
try
{
Looper.loop();
}
catch (RuntimeException ex)
{
Log.d("Dialog Error", ex.toString());
}
return dialogResult;
And below is how I am initialising the common class
Common common = new Common(getApplicationContext());
Instead of getApplicationContext, I've tried using this but doesn't make any difference.
I just don't understand what is happening here.
Thanks for any help you can provide
The problem is in your showYesNoDialog(). What does the boolean parameter for your showYesNoDialog() method do?
How can I implement a Preference that displays a simple yes/no confirmation dialog?
For an example, see Browser->Setting->Clear Cache.
That is a simple alert dialog, Federico gave you a site where you can look things up.
Here is a short example of how an alert dialog can be built.
new AlertDialog.Builder(this)
.setTitle("Title")
.setMessage("Do you really want to whatever?")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Toast.makeText(MainActivity.this, "Yaay", Toast.LENGTH_SHORT).show();
}})
.setNegativeButton(android.R.string.no, null).show();
Android comes with a built-in YesNoPreference class that does exactly what you want (a confirm dialog with yes and no options). See the official source code here.
Unfortunately, it is in the com.android.internal.preference package, which means it is a part of Android's private APIs and you cannot access it from your application (private API classes are subject to change without notice, hence the reason why Google does not let you access them).
Solution: just re-create the class in your application's package by copy/pasting the official source code from the link I provided. I've tried this, and it works fine (there's no reason why it shouldn't).
You can then add it to your preferences.xml like any other Preference. Example:
<com.example.myapp.YesNoPreference
android:dialogMessage="Are you sure you want to revert all settings to their default values?"
android:key="com.example.myapp.pref_reset_settings_key"
android:summary="Revert all settings to their default values."
android:title="Reset Settings" />
Which looks like this:
Use Intent Preference if you are using preference xml screen or you if you are using you custom screen then the code would be like below
intentClearCookies = getPreferenceManager().createPreferenceScreen(this);
Intent clearcookies = new Intent(PopupPostPref.this, ClearCookies.class);
intentClearCookies.setIntent(clearcookies);
intentClearCookies.setTitle(R.string.ClearCookies);
intentClearCookies.setEnabled(true);
launchPrefCat.addPreference(intentClearCookies);
And then Create Activity Class somewhat like below, As different people as different approach you can use any approach you like this is just an example.
public class ClearCookies extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
showDialog();
}
/**
* #throws NotFoundException
*/
private void showDialog() throws NotFoundException {
new AlertDialog.Builder(this)
.setTitle(getResources().getString(R.string.ClearCookies))
.setMessage(
getResources().getString(R.string.ClearCookieQuestion))
.setIcon(
getResources().getDrawable(
android.R.drawable.ic_dialog_alert))
.setPositiveButton(
getResources().getString(R.string.PostiveYesButton),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
//Do Something Here
}
})
.setNegativeButton(
getResources().getString(R.string.NegativeNoButton),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
//Do Something Here
}
}).show();
}}
As told before there are number of ways doing this. this is one of the way you can do your task, please accept the answer if you feel that you have got it what you wanted.