Menu button can only be clicked one time - android

I added a custom menu to the menu button using the following code:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
if (getDisplayedView() instanceof WorkspaceView) {
((WorkspaceView) getDisplayedView()).showEditMenu();
}
return true;
}
and
public void showEditMenu() {
new EditMenu(lexs, ((Project) projects.getSelectedItem()).getName(), ((ProjectList) projectsList.getSelectedItem()).getName()).show();
}
The EditMenu is implemented the following way:
public class EditMenu {
private final String DELETE_PROJECT = "Projekt löschen";
private final String DELETE_LIST = "Liste löschen";
private final String RENAME_PROJECT = "Projekt umbenennen";
private final String RENAME_LIST = "Liste umbenennen";
private final String CLOSE = "Menü schliessen";
private Context context;
private String projectName;
private String listName;
private AlertDialog alert;
private final CharSequence[] items = {DELETE_PROJECT, DELETE_LIST, RENAME_PROJECT, RENAME_LIST, CLOSE};
public EditMenu(Context context, String projectName, String listName) {
this.context = context;
this.projectName = projectName;
this.listName = listName;
}
public void show() {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(projectName + ": " + listName);
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals(DELETE_PROJECT)) {
deleteProject();
} else if (items[item].equals(DELETE_LIST)) {
deleteList();
} else if (items[item].equals(RENAME_PROJECT)) {
renameProject();
} else if (items[item].equals(RENAME_LIST)) {
renameList();
} else if (items[item].equals(CLOSE)) {
close();
}
}
});
alert = builder.create();
alert.show();
}
private void deleteProject() {
}
private void deleteList() {
}
private void renameProject() {
}
private void renameList() {
}
private void close() {
}
}
This works correctly if I click the menu button the first time. But if the context menu is closed and i click the menu button a second time, nothing happens.
I also tried to call
alert.close(), alert.hide(), alert.dismiss(), etc in the method close(), but it doesn't improve the situation. any hints? thankS¨!

Since there is no other answer in almost 3 weeks, I'll answer my question by myself:
Instead of overwriting
public boolean onCreateOptionsMenu(Menu menu)
one has to override
public boolean onPrepareOptionsMenu(Menu menu)
Here a short example how to do it:
In the activity there is the following code:
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
showMenu();
return true;
}
private void showMenu() {
EditMenu menu = new EditMenu(this, "Pacman Menu");
menu.show();
}
Then the clsas EditMenu looks for example the following way:
public class EditMenu {
private final String QUIT = "Quit";
private final String RESTART = "New Game";
private final String SOUND = "Switch Sound";
private final String PAUSE = "Un/pause";
private final CharSequence[] items = new CharSequence[] {QUIT, RESTART, SOUND, PAUSE};
private Context context;
private String title;
private AlertDialog alert;
private MenuListener listener = new MenuListener();
public EditMenu(Context context, String title) {
this.context = context;
this.title = title;
}
public void show() {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setIcon(R.drawable.splashscreen);
builder.setTitle(title);
builder.setItems(items, listener);
alert = builder.create();
alert.show();
}
private class MenuListener implements DialogInterface.OnClickListener {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals(QUIT)) {
((PacmanGame) context).quitGame();
} else if (items[item].equals(RESTART)) {
((PacmanGame) context).restart();
} else if (items[item].equals(SOUND)) {
Sound.setSoundOn(! Sound.isSoundOn());
} else if (items[item].equals(PAUSE)) {
((PacmanGame) context).getGameBoard().setPausing(!(((PacmanGame) context).getGameBoard().isPaused()));
}
}
}
}

Related

Android dialog will not bring text to underlying fragment

I am currently attempting to have a custom dialog on a fragment to bring text back to the fragment. I have the dialog setup but when I click on the button to bring up the dialog I get this error.
java.lang.ClassCastException: com.example.android.app.MainActivity#4c01a76must implement StatusDialogListener
I then found this stack post talking about the issue
From reading the error and the stack post it seems that the issue is that I have to implement the dialog class onto the activity that is connected to the fragment.
So I implemented the listener into my main activity
public class MainActivity extends AppCompatActivity implements ... Status_Dialog.StatusDialogListner
After implementing it, I got the error below:
Class 'MainActivity' must either be declared abstract or implement abstract method 'applyText(String)' in 'StatusDialogListner
Which I fixed by adding the code below to the Activity:
#Override
public void applyText(String status) {
}
This allows the app to run and display the dialog with no errors.
The issue is now my adapter will not get the text from the dialog so I believe it is to do with the fact that I also have an applyText in my fragment and main activity when I ran the debugger applytext in the fragment was never called. I am lost at this point
Code
Dialog
public class Status_Dialog extends AppCompatDialogFragment {
private EditText editTextStatus;
private StatusDialogListner listner;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.layout_status_dialog, null);
editTextStatus = view.findViewById(R.id.new_status);
builder.setView(view)
.setTitle("Change Status")
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
})
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String status = editTextStatus.getText().toString();
listner.applyText(status);
}
});
return builder.create();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
listner = (StatusDialogListner) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() + "must implement StatusDialogListener");
}
}
public interface StatusDialogListner {
void applyText(String status);
}
}
Fragment
public class profile_fragment extends Fragment implements Status_Dialog.StatusDialogListner {
private static final int GALLERY_PICK = 1;
private DatabaseReference mUserDatabase;
//Android Layout
private FirebaseUser mCurrentUser;
private CircleImageView mDisplayImage;
private TextView mName;
private TextView mStatus;
private Button mStatusBtn;
private Button mImageBtn;
private ProgressDialog mProgressDialog;
private StorageReference mImageStorage;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListner;
private static final String KEY_NAME = "name";
private static final String KEY_STATUS = "status";
private static final String KEY_IMAGE = "image";
private static final String TAG = "user_profile";
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_profile_fragment, container, false);
mDisplayImage = view.findViewById(R.id.profile_picture);
mName = view.findViewById(R.id.profile_user_name);
mStatus = view.findViewById(R.id.profile_user_status);
mStatusBtn = view.findViewById(R.id.profile_change_status_btn);
mImageBtn = view.findViewById(R.id.profile_change_image_btn);
mImageStorage = FirebaseStorage.getInstance().getReference();
mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
final String current_uid = mCurrentUser.getUid();
DocumentReference mUsersDB = db.collection("Users").document(current_uid);
// FirebaseUser currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser() ;
// Toast.makeText(this, "ttt" + currentFirebaseUser.getUid(), Toast.LENGTH_SHORT).show();
mStatusBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openDialog();
/*
String status_value = mStatus.getText().toString();
Intent status_intent = new Intent(getActivity(), change_status.class);
status_intent.putExtra("status_value", status_value);
startActivity(status_intent);
*/
}
});
mImageBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(galleryIntent, "Select Image"), GALLERY_PICK);
/*
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.start(SettingsActivity.this);
*/
}
});
mUsersDB.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if (documentSnapshot.exists()) {
String name = documentSnapshot.getString(KEY_NAME);
mName.setText(name);
String status = documentSnapshot.getString(KEY_STATUS);
mStatus.setText(status);
FirebaseUser currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
} else {
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
return view;
}
public void openDialog(){
Status_Dialog status_dialog = new Status_Dialog();
status_dialog.show(getActivity().getSupportFragmentManager(), "TEST?");
}
#Override
public void applyText(String status) {
mStatus.setText(status);
}
...
Problem is here:
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
listner = (StatusDialogListner) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() + "must implement StatusDialogListener");
}
}
Note that listner is set during the onAttach and it is receiving the instance of Context. In other words, it is receiving the instance of the host activity (That's why you had to implement the interface in the MainActivity)
I think you can update your code as follows:
1) Remove this from the dialog. This way, your activity no longer must implement StatusDialogListener
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
listner = (StatusDialogListner) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() + "must implement StatusDialogListener");
}
}
2) Update this on Dialog:
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if(listner != null) { // ADD THIS NULL CHECK SINCE LISTNER MAY BE NULL
String status = editTextStatus.getText().toString();
listner.applyText(status);
}
}
});
3) Add this to the dialog:
public void setListener(StatusDialogListner newListener) {
this.listner = newListener;
}
4) Update this on the fragment:
public void openDialog(){
Status_Dialog status_dialog = new Status_Dialog();
status_dialog.setListener(this); // ADD THIS NEW LINE
status_dialog.show(getActivity().getSupportFragmentManager(), "TEST?");
}
5) Remove below code from MainActivity
// Remove the implementation of Status_Dialog.StatusDialogListner from MainActivity
// And remove the method below:
#Override
public void applyText(String status) {
}

How to get user ID or info in onAuthenticationSucceeded method for android fingerprint

I am implementing an android fingerprint authentication. I want to know which user, who has registered in device before, is authenticating. Is there any information about the user, who has registered and is valid for the device, in the FingerprintManager.AuthenticationResult argument in onAuthenticationSucceeded method?!
I am using this sample.
this is my class, which is implementing FingerprintManager.AuthenticationCallback:
public class FingerprintUiHelper extends FingerprintManager.AuthenticationCallback {
private static final long ERROR_TIMEOUT_MILLIS = 1600;
private static final long SUCCESS_DELAY_MILLIS = 1300;
private final FingerprintManager mFingerprintManager;
private final ImageView mIcon;
private final TextView mErrorTextView;
private final Callback mCallback;
private CancellationSignal mCancellationSignal;
private boolean mSelfCancelled;
/**
* Constructor for {#link FingerprintUiHelper}.
*/
FingerprintUiHelper(FingerprintManager fingerprintManager,
ImageView icon, TextView errorTextView, Callback callback) {
mFingerprintManager = fingerprintManager;
mIcon = icon;
mErrorTextView = errorTextView;
mCallback = callback;
}
public boolean isFingerprintAuthAvailable() {
// The line below prevents the false positive inspection from Android Studio
// noinspection ResourceType
return mFingerprintManager.isHardwareDetected()
&& mFingerprintManager.hasEnrolledFingerprints();
}
public void startListening(FingerprintManager.CryptoObject cryptoObject) {
if (!isFingerprintAuthAvailable()) {
return;
}
mCancellationSignal = new CancellationSignal();
mSelfCancelled = false;
// The line below prevents the false positive inspection from Android Studio
// noinspection ResourceType
mFingerprintManager
.authenticate(cryptoObject, mCancellationSignal, 0 /* flags */, this, null);
mIcon.setImageResource(R.drawable.ic_fp_40px);
}
public void stopListening() {
if (mCancellationSignal != null) {
mSelfCancelled = true;
mCancellationSignal.cancel();
mCancellationSignal = null;
}
}
#Override
public void onAuthenticationError(int errMsgId, CharSequence errString) {
if (!mSelfCancelled) {
showError(errString);
mIcon.postDelayed(new Runnable() {
#Override
public void run() {
mCallback.onError();
}
}, ERROR_TIMEOUT_MILLIS);
}
}
#Override
public void onAuthenticationHelp(int helpMsgId, CharSequence helpString) {
showError(helpString);
}
#Override
public void onAuthenticationFailed() {
showError(mIcon.getResources().getString(
R.string.fingerprint_not_recognized));
}
#Override
public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) {
mErrorTextView.removeCallbacks(mResetErrorTextRunnable);
mIcon.setImageResource(R.drawable.ic_fingerprint_success);
mErrorTextView.setTextColor(
mErrorTextView.getResources().getColor(R.color.success_color, null));
mErrorTextView.setText(
mErrorTextView.getResources().getString(R.string.fingerprint_success));
mIcon.postDelayed(new Runnable() {
#Override
public void run() {
mCallback.onAuthenticated();
}
}, SUCCESS_DELAY_MILLIS);
}
private void showError(CharSequence error) {
mIcon.setImageResource(R.drawable.ic_fingerprint_error);
mErrorTextView.setText(error);
mErrorTextView.setTextColor(
mErrorTextView.getResources().getColor(R.color.warning_color, null));
mErrorTextView.removeCallbacks(mResetErrorTextRunnable);
mErrorTextView.postDelayed(mResetErrorTextRunnable, ERROR_TIMEOUT_MILLIS);
}
private Runnable mResetErrorTextRunnable = new Runnable() {
#Override
public void run() {
mErrorTextView.setTextColor(
mErrorTextView.getResources().getColor(R.color.hint_color, null));
mErrorTextView.setText(
mErrorTextView.getResources().getString(R.string.fingerprint_hint));
mIcon.setImageResource(R.drawable.ic_fp_40px);
}
};
public interface Callback {
void onAuthenticated();
void onError();
}
}

RealmObject not saving data

I am saving data to a RealmObject then adding it to my Realm. After leaving the activity and returning the RealmObject is retrieved and the EditText are loaded with the appropriate data. All the EditText but one, Company Address, are loading correctly and I can't figure out why when all save and loading information is the same. Any ideas?
Activity
public class NewLocation extends ActionBarActivity {
public EditText editCoName;
public EditText editCoAddress;
public EditText editCoContact;
public EditText editSqFt;
public EditText editTaxed;
public EditText editConcerns;
private Realm realm;
public CompanyInfo companyInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_location);
findViewById(R.id.button3).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SaveInfo();
Intent i = new Intent(NewLocation.this, RoomList.class);
startActivity(i);
}
});
editCoName = (EditText) findViewById(R.id.CoName);
editCoAddress = (EditText) findViewById(R.id.CoAddress);
editCoContact = (EditText) findViewById(R.id.CoContact);
editSqFt = (EditText) findViewById(R.id.SqFt);
editTaxed = (EditText) findViewById(R.id.Taxed);
editConcerns = (EditText) findViewById(R.id.Concerns);
//initialize realm and make CompanyInfo object if there is not already one
realm = Realm.getInstance(this);
CompanyInfo result = realm.where(CompanyInfo.class).findFirst();
if (result == null){
realm.beginTransaction();
companyInfo = realm.createObject(CompanyInfo.class);
companyInfo.setName(editCoName.getText().toString());
companyInfo.setAddress(editCoAddress.getText().toString());
companyInfo.setContact(editCoContact.getText().toString());
companyInfo.setTaxed(editTaxed.getText().toString());
companyInfo.setSqFt(editSqFt.getText().toString());
companyInfo.setConcerns(editConcerns.getText().toString());
realm.commitTransaction();
}
else {
editCoName.setText(result.getName());
editCoAddress.setText(result.getAddress());
editCoContact.setText(result.getContact());
editTaxed.setText(result.getTaxed());
editSqFt.setText(result.getSqFt());
editConcerns.setText(result.getConcerns());
}
}
#Override
protected void onResume() {
super.onResume();
LoadInfo();
}
#Override
protected void onPause() {
super.onPause();
SaveInfo();
}
#Override
protected void onDestroy() {
super.onDestroy();
realm.close();
}
public void SaveInfo() {
//save all info from the page
companyInfo = realm.where(CompanyInfo.class).findFirst();
realm.beginTransaction();
companyInfo.setName(editCoName.getText().toString());
companyInfo.setAddress(editCoAddress.getText().toString());
companyInfo.setContact(editCoContact.getText().toString());
companyInfo.setTaxed(editTaxed.getText().toString());
companyInfo.setSqFt(editSqFt.getText().toString());
companyInfo.setConcerns(editConcerns.getText().toString());
realm.copyToRealmOrUpdate(companyInfo);
realm.commitTransaction();
}
public void LoadInfo() {
//load info fom the CompanyInfo and put it into EditTexts
companyInfo = realm.where(CompanyInfo.class).findFirst();
if (companyInfo != null) {
editCoName.setText(companyInfo.getName());
editCoAddress.setText(companyInfo.getAddress());
editCoContact.setText(companyInfo.getContact());
editTaxed.setText(companyInfo.getTaxed());
editSqFt.setText(companyInfo.getSqFt());
editConcerns.setText(companyInfo.getConcerns());
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_new_location, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
switch(item.getItemId())
{
case R.id.home:
startActivity(new Intent(getApplicationContext(), MainPage.class));
break;
}
return super.onOptionsItemSelected(item);
}
}
CompanyInfo class
public class CompanyInfo extends RealmObject{
#PrimaryKey
private String Name;
#Ignore
private String Address;
private String Contact;
private String sqFt;
private String taxed;
private String concerns;
private RealmList<Rooms> rooms = new RealmList<>();
public RealmList<Rooms> getRooms() {
return rooms;
}
public void setRooms(RealmList<Rooms> rooms) {
this.rooms = rooms;
}
public String getName() {
return Name;
}
public String getAddress() {
return Address;
}
public String getContact() {
return Contact;
}
public String getSqFt() {
return sqFt;
}
public String getTaxed() {
return taxed;
}
public String getConcerns() {
return concerns;
}
public void setName(String coName) {
this.Name = coName;
}
public void setAddress(String coAddress) {
this.Address = coAddress;
}
public void setContact(String coContact) {
this.Contact = coContact;
}
public void setSqFt(String sqFt) {
this.sqFt = sqFt;
}
public void setTaxed(String taxed) {
this.taxed = taxed;
}
public void setConcerns(String concerns) {
this.concerns = concerns;
}
}
You have an #Ignore annotation on CompanyInfo#Adresse, remove it and Realm will save the adress.

I dont know how to change ok glass phrase in google glass

I want to make glass application with offline voice recognition with no ok glass
what I want to know is changing ok glass to other words ( something like "start").
I saw the source decompiled GlassHome.apk and GlassVoice.apk.
I knew that setting to ok glass is related with VoiceInputHelper, voice_label_ok_glass in String.xml
so I tried to change all of string "ok glass" to "nice"(temp guard phrase) in String.xml
but when I said any word (like "hahaha" or "kakaka") , all of word I said is recognized to my guard phrase ("nice") by VoiceService.
what should I do for changing "ok glass" to my guard phrase and working it right ???????
(P.S sorry my bad english. I hope you understand what question means)
here is my code ( I tried to set VoiceConfig to "nice")
public class MainActivity extends GlassActivity implements VoiceListener {
public static final String TEST_SERVICE_EXTRAS_KEY = "serviceExtras";
private ImageView gradientView;
private GuardHintAnimator guardHintAnimator;
private TextView guardPhraseView;
private boolean isRunning = false;
private final FormattingLogger logger = FormattingLoggers.getLogger(this);
private VoiceConfig onWindowFocusChangedRecoverConfig;
private VoiceConfig voiceConfig;
#VisibleForTesting
VoiceInputHelper voiceInputHelper;
private IVoiceMenuDialog voiceMenuDialog;
public FormattingLogger getLogger()
{
return this.logger;
}
public boolean isRunning()
{
return this.isRunning;
}
#Override
protected void onCreateInternal(Bundle bundle) {
super.onCreateInternal(bundle);
this.voiceInputHelper = new VoiceInputHelper(this, new DelegatingVoiceListener(this)
{
public VoiceConfig onVoiceCommand(VoiceCommand paramAnonymousVoiceCommand)
{
if ((!MainActivity.this.hasWindowFocus()) && (!MainActivity.this.isMessageShowing()))
{
MainActivity.this.logger.d("Ignoring voice command because we don't have window focus.", new Object[0]);
return null;
}
Log.d("listener",paramAnonymousVoiceCommand.toString());
//return super.onVoiceCommand(paramAnonymousVoiceCommand);
return null;
}
}, getVoiceServiceExtras());
}
protected void onPauseInternal()
{
this.isRunning = false;
super.onPauseInternal();
closeVoiceMenu();
this.voiceInputHelper.setVoiceConfig(VoiceConfig.OFF);
this.voiceInputHelper.unregisterGrammarLoaders();
}
public void closeVoiceMenu()
{
if (this.voiceMenuDialog != null)
{
this.voiceMenuDialog.dismiss(false);
this.voiceMenuDialog = null;
}
}
public void onPrepareVoiceMenu(VoiceMenuDialog paramVoiceMenuDialog) {}
public boolean onResampledAudioData(byte[] paramArrayOfByte, int paramInt1, int paramInt2)
{
return false;
}
protected void onResumeInternal()
{
this.isRunning = true;
super.onResumeInternal();
this.voiceInputHelper.registerGrammarLoaders();
this.voiceInputHelper.setWantAudioData(shouldProvideAudioData());
NetworkUtil.checkNetwork();
VoiceConfig localVoiceConfig = new VoiceConfig();
String[] arrayOfString = new String[1];
arrayOfString[0] = "nice";
localVoiceConfig = localVoiceConfig.setCustomPhrases(arrayOfString).setShouldSaveAudio(true);
voiceInputHelper.setVoiceConfig(localVoiceConfig);
}
public boolean isVoiceMenuShowing()
{
return (this.voiceMenuDialog != null) && (this.voiceMenuDialog.isShowing());
}
public VoiceConfig onVoiceCommand(VoiceCommand paramVoiceCommand)
{
Log.d("hhh",paramVoiceCommand.toString());
this.logger.w("Unrecognized voice command: %s", new Object[] { paramVoiceCommand });
return null;
}
protected Bundle getVoiceServiceExtras()
{
Bundle localBundle = new Bundle();
/* if (getIntent().hasExtra("serviceExtras"))
{
localBundle.putAll(getIntent().getBundleExtra("serviceExtras"));
}*/
return localBundle;
}
public void setVoiceConfig(VoiceConfig paramVoiceConfig)
{
this.voiceConfig = paramVoiceConfig;
if (paramVoiceConfig != null) {
this.voiceInputHelper.setVoiceConfig(this.voiceConfig);
}
}
public boolean shouldProvideAudioData()
{
return false;
}
public void onVoiceConfigChanged(VoiceConfig paramVoiceConfig, boolean paramBoolean) {}
}
DelegatingVoiceListener :
class DelegatingVoiceListener implements VoiceListener
{
private final VoiceListener delegate;
DelegatingVoiceListener(VoiceListener paramVoiceListener)
{
this.delegate = paramVoiceListener;
}
public FormattingLogger getLogger()
{
return this.delegate.getLogger();
}
public boolean isRunning()
{
return this.delegate.isRunning();
}
public boolean onResampledAudioData(byte[] paramArrayOfByte, int paramInt1, int paramInt2)
{
return this.delegate.onResampledAudioData(paramArrayOfByte, paramInt1, paramInt2);
}
public VoiceConfig onVoiceCommand(VoiceCommand paramVoiceCommand)
{
return this.delegate.onVoiceCommand(paramVoiceCommand);
}
public void onVoiceConfigChanged(VoiceConfig paramVoiceConfig, boolean paramBoolean)
{
this.delegate.onVoiceConfigChanged(paramVoiceConfig, paramBoolean);
}
}
You need to request special permissions in your manifest to implement unlisted voice commands. Go here. However, I doubt you can change the 'ok glass' voice command. You can still try if you really want to.

What is the use of that code in my file?

i had made an application. And i wanted to add an End User license agreement to my app. So i had created a class to do it...
firstly i used to show my EULA with the inbuilt AlertDialog of android.
it worked fine..
Then i had made my own custom AlertDialog, and then tried to show the ELUA on my custom dialog. Now it works fine... The files were like...
//my Eula.java file...
//Gets the Eula file from assests folder...
class Eula {
private static final String ASSET_EULA = "EULA";
private static final String PREFERENCE_EULA_ACCEPTED = "eula.accepted";
private static final String PREFERENCES_EULA = "eula";
static interface OnEulaAgreedTo {
void onEulaAgreedTo();
}
static boolean show(final Activity activity)
{
final SharedPreferences preferences = activity.getSharedPreferences(PREFERENCES_EULA,
Activity.MODE_PRIVATE);
if (!preferences.getBoolean(PREFERENCE_EULA_ACCEPTED, false))
{
final CustomDialog.Builder builder = new CustomDialog.Builder(activity);
builder.setTitle(R.string.app_name1);
//builder.setCancelable(true);
builder.setPositiveButton(R.string.eula_accept, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
accept(preferences);
/*if(activity instanceof OnEulaAgreedTo)
{
((OnEulaAgreedTo) activity).onEulaAgreedTo();
}*/
dialog.dismiss();
}
});
builder.setNegativeButton(R.string.eula_refuse, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which) {
refuse(activity);
}
});
CharSequence s = readEula(activity);
builder.setMessage(s.toString());
builder.create().show();
return false;
}
return true;
}
private static void accept(SharedPreferences preferences) {
preferences.edit().putBoolean(PREFERENCE_EULA_ACCEPTED, true).commit();
}
private static void refuse(Activity activity) {
activity.finish();
}
private static CharSequence readEula(Activity activity) {
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(activity.getAssets().open(ASSET_EULA)));
String line;
StringBuilder buffer = new StringBuilder();
while ((line = in.readLine()) != null) buffer.append(line).append('\n');
return buffer;
} catch (IOException e) {
return "";
} finally {
closeStream(in);
}
}
private static void closeStream(Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
}
}
}
}
And then i have my CustomDialog file
//my CustomDialog.java file...
public class CustomDialog extends Dialog {
private static final String ASSET_EULA = "EULA";
public CustomDialog(Context context, int theme) {
super(context, theme);
}
public CustomDialog(Context context) {
super(context);
}
public static class Builder {
private Context context;
private String title;
private String message;
private String positiveButtonText;
private String negativeButtonText;
//private String cancelButtonText;
private View contentView;
private DialogInterface.OnClickListener
positiveButtonClickListener,
negativeButtonClickListener;
public Builder(Context context) {
this.context = context;
}
public Builder setMessage(String message) {
this.message = message;
return this;
}
public Builder setMessage(int message) {
this.message = (String) context.getText(message);
return this;
}
public Builder setTitle(int title) {
this.title = (String) context.getText(title);
return this;
}
public Builder setTitle(String title) {
this.title = title;
return this;
}
public Builder setContentView(View v) {
this.contentView = v;
return this;
}
public Builder setPositiveButton(int positiveButtonText,
DialogInterface.OnClickListener listener) {
this.positiveButtonText = (String) context
.getText(positiveButtonText);
this.positiveButtonClickListener = listener;
return this;
}
public Builder setPositiveButton(String positiveButtonText,
DialogInterface.OnClickListener listener) {
this.positiveButtonText = positiveButtonText;
this.positiveButtonClickListener = listener;
return this;
}
public Builder setNegativeButton(int negativeButtonText,
DialogInterface.OnClickListener listener) {
this.negativeButtonText = (String) context
.getText(negativeButtonText);
this.negativeButtonClickListener = listener;
return this;
}
public Builder setNegativeButton(String negativeButtonText,
DialogInterface.OnClickListener listener) {
this.negativeButtonText = negativeButtonText;
this.negativeButtonClickListener = listener;
return this;
}
public CustomDialog create() {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// instantiate the dialog with the custom Theme
final CustomDialog dialog = new CustomDialog(context,
R.style.Dialog);
View layout = inflater.inflate(R.layout.dialog, null);
dialog.addContentView(layout, new LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
// set the dialog title
((TextView) layout.findViewById(R.id.title)).setText(title);
// set the confirm button
if (positiveButtonText != null)
{
((Button) layout.findViewById(R.id.positiveButton)).setText(positiveButtonText);
if (positiveButtonClickListener != null)
{
((Button) layout.findViewById(R.id.positiveButton)).setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
positiveButtonClickListener.onClick(dialog, DialogInterface.BUTTON_POSITIVE);
}
});
}
} else {
// if no confirm button just set the visibility to GONE
layout.findViewById(R.id.positiveButton).setVisibility(
View.GONE);
}
// set the cancel button
if (negativeButtonText != null) {
((Button) layout.findViewById(R.id.negativeButton))
.setText(negativeButtonText);
if (negativeButtonClickListener != null) {
((Button) layout.findViewById(R.id.negativeButton))
.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
negativeButtonClickListener.onClick(dialog, DialogInterface.BUTTON_NEGATIVE);
}
});
}
} else {
// if no confirm button just set the visibility to GONE
layout.findViewById(R.id.negativeButton).setVisibility(
View.GONE);
}
// set the content message
if (message != null) {
((TextView) layout.findViewById(
R.id.message)).setText(message);
} else if (contentView != null) {
// if no message set
// add the contentView to the dialog body
((LinearLayout) layout.findViewById(R.id.content))
.removeAllViews();
((LinearLayout) layout.findViewById(R.id.content))
.addView(contentView,
new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
}
dialog.setContentView(layout);
return dialog;
}
public void dismiss()
{
this.dismiss();
}
public void setCancelable(boolean b) {
// TODO Auto-generated method stub
this.setCancelable(true);
}
}
}
Atfirst, the onClickfor setPositive button for eula.java file was like
public void onClick(DialogInterface dialog, int which)
{
accept(preferences);
if(activity instanceof OnEulaAgreedTo)
{
((OnEulaAgreedTo) activity).onEulaAgreedTo();
}
}
it worked fine for the inbuilt AlertDialog. but when i changed it with my custom dialog, that codition is resulting false always...
Can anyone tell me what that code is meant for?
For dialog disappearing you should use Dialog.dismiss(). You can dismiss dialog just at the end of positive button behavior.
When you click on refuse button you finish activity, and that's why you dialog dismisses.
The issue may be in the following condition. please check the activity instance whether it agrres the condition?
if(activity instanceof OnEulaAgreedTo)
{
((OnEulaAgreedTo) activity).onEulaAgreedTo();
}

Categories

Resources