How to make AlertDialog view in Input method Service? - java

I would like to make an input method which is used only for SoftKeyboard. My how to make popup onkey event in input method.
I am creating Dialog but here is problem you see my logcat:
09-14 11:16:54.349: E/MessageQueue-JNI(7172): at android.inputmethodservice.KeyboardView.detectAndSendKey(KeyboardView.java:824)
Softkeyboard.java
Here java code
public void onKey(int primaryCode, int[] keyCodes) {
if (primaryCode == -2) {
// add this to your code
dialog = builder.create();
Window window = dialog.getWindow();
WindowManager.LayoutParams lp = window.getAttributes();
lp.token = mInputView.getWindowToken();
lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG;
window.setAttributes(lp);
window.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
// end addons
builder.show();
}
Thanks for advance..

You need to have ACTION_MANAGE_OVERLAY_PERMISSION permission to open/display Alert onkey event in input method.
Before you set your custom Keyboard Check for Overlay Permission.
final boolean overlayEnabled = Settings.canDrawOverlays(MainActivity.this);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !overlayEnabled) {
openOverlaySettings();
}
#TargetApi(Build.VERSION_CODES.M)
private void openOverlaySettings() {
final Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + getPackageName()));
try {
startActivityForResult(intent, RC_OVERLAY);
} catch (ActivityNotFoundException e) {
Log.e("MainActivity", e.getMessage());
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case RC_OVERLAY:
final boolean overlayEnabled = Settings.canDrawOverlays(this);
if (overlayEnabled) {
preferenceManager.setBooleanPref(IS_CYBER_BULLING_ON, true);
Intent intent = new Intent(MainActivity.this, ImePreferences.class);
startActivity(intent);
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
} else {
// switchCyberBulling.setChecked(false);
}
// Do something...
break;
}
}
Then inside your SoftKeyboard.java class, put code for alert dialog & set alert type of "TYPE_APPLICATION_OVERLAY".
AlertDialog.Builder builder = new AlertDialog.Builder(this)
//set icon
.setIcon(android.R.drawable.ic_dialog_alert)
//set title
.setTitle("Warning!")
//set message
.setMessage("This is alert dialog!")
//set positive button
.setPositiveButton("Okay", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//set what would happen when positive button is clicked
dialogInterface.dismiss();
}
})
//set negative button
.setNegativeButton("Dismiss", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//set what should happen when negative button is clicked
dialogInterface.dismiss();
}
});
AlertDialog alertDialog = builder.create();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);
}else{
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
}
alertDialog.show();
Do not forget for Draw Overlay Permission. Hope this helps you. :)

Related

Dialogue box does not show up

I am creating a dialogue box that should appear to the user in case of the GPS service is disabled. But what is happening is, although I disabled the service manually to force the dialogue appear, the App starts and nothing is happening.
The code below shows how I tried to create the dialogue box and when. Please let me know if there is any mistake.
JavaCode:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gpstest00);
locMgr = (LocationManager) getSystemService(LOCATION_SERVICE);
gpsEnable = locMgr.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!gpsEnable) {
showGPSDialogueBox();
}
locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 1, this.locationListener);
}
/*if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
}*/
private void showGPSDialogueBox() {
AlertDialog.Builder alertDialogue = new AlertDialog.Builder(this);
alertDialogue.setTitle("GPS Settings");
alertDialogue.setMessage("GPS is deactivated. Do you want to switch " + to settings menu to activate it?");
alertDialogue.setPositiveButton("Settings",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
alertDialogue.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
}// Enf of showDialogueBox function.
You need to call show function for the dialog box to show
alertDialogue.show();
You need to create AlertDialog from AlertDialog.Builder object then show the AlertDialog using show() method as follows...
AlertDialog dialog = alertDialogue.create();
dialog.show();
Update your showGPSDialogueBox() as below...
private void showGPSDialogueBox() {
AlertDialog.Builder alertDialogue = new AlertDialog.Builder(this);
alertDialogue.setTitle("GPS Settings");
alertDialogue.setMessage("GPS is deactivated. Do you want to switch " +
" to settings menu to activate it?");
alertDialogue.setPositiveButton("Settings",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
alertDialogue.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
AlertDialog dialog = alertDialogue.create();
dialog.show();
}

Custom Dialog with game score android

I've got a huge problem. When I had AlertBox everything was OK, but I would change it to custom dialog box with pretty good graphic.
With AlertBox it was displaying the current scores and highscore.
When I changed it to Custom Dialog box it's showing nothing.
CustomDialogClass.java
public class CustomDialogClass extends Dialog
{
public CustomDialogClass(Context context) {
super(context);
// TODO Auto-generated constructor stub
/** It will hide the title */
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_dialog);
}
}
GameActivity.java (fragments with custom dialog box)
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
surfaceCreated = false;
stopDrawingThread();
}
public void customizeDialog() {
int highest = PrefUtil.getHighestScore(this);
String text = null;
if (currentPoint > highest) {
highest = currentPoint;
PrefUtil.setHighestScore(this, currentPoint);
} else {
}
text = "Current Points: " + currentPoint + "\nThe Best Score: " + highest;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Game Over");
builder.setMessage(text);
builder.setPositiveButton("Try Again", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
playSwooshing();
restart();
}
});
builder.setNegativeButton("Exit Game", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(GameActivity.this,Bye.class);
startActivity(intent);
playSwooshing();
finish();
}
});
builder.setCancelable(false);
alertDialog = builder.show();
}
and the other fragment:
private void onGameOver() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (!isFinishing()) {
soundPool.play(soundIds[SOUND_DIE], 0.5f, 0.5f, 1, 0, 1);
CustomDialogClass customizeDialog = new CustomDialogClass(GameActivity.this);
customizeDialog.show(); }
}
});
}
Where is a problem? Can someone fix it?
Now it's showing only my layout file, without any data.
Thanks!
It's not displaying your data because you're not setting your data. In your middle code fragment where you're creating your dialog using a Builder you're not using your custom dialog, so apparently that code is no longer being called. Likewise in your last fragment where you do create a custom dialog, you're not setting any the data.
See the documentation:
If you want a custom layout in a dialog, create a layout and add it to an AlertDialog by calling setView() on your AlertDialog.Builder object.
By default, the custom layout fills the dialog window, but you can still use AlertDialog.Builder methods to add buttons and a title.

My code seems to be sound but any time I click the submit button it does nothing

Alright I am comparing the text that the user has input to the edittext and comparing to the answer that is there in the String.xml. The code seems completely sounds and error-less but it doesn't work at all. Any help would be appreciated.
package com.example.italianapp;
public class Pictures<sButton> extends MainActivity
{
int level=0; // integer that will keep track of users progress
Button sButton; // represents the submit button
EditText mEdit; // text area where the user types answer
private SensorManager mSensorManager; // new sensor
private ShakeEventListener mSensorListener; // variable that listens for movement
// if the back button is pressed, return to easy menu
public void onBackPressed()
{
Intent backIntent = new Intent(Pictures.this, Learningmenu.class);
startActivity(backIntent);
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.words); // uses easy_mode1 xml
// shared preferences variable that will act as a holder of users progress
final SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
AlertDialog.Builder hint = new AlertDialog.Builder(this); // hint alert dialog box
hint.setMessage("Would you like a hint?");
hint.setCancelable(false);
hint.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
// if user clicks yes, toast pops up providing a hint
public void onClick(DialogInterface dialog, int id)
{
Toast.makeText(Pictures.this, "You have two of these on your body", Toast.LENGTH_LONG).show();
}
});
hint.setNegativeButton("No", new DialogInterface.OnClickListener()
{
// if the user clicks no the level is loaded again
public void onClick(DialogInterface dialog, int id)
{
Intent intent = new Intent(Pictures.this, Pictures.class);
startActivity(intent);
dialog.cancel();
}
});
final AlertDialog hintAlert = hint.create();
hintAlert.setTitle("Hint");
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mSensorListener = new ShakeEventListener();
mSensorListener.setOnShakeListener(new ShakeEventListener.OnShakeListener()
{
// when the user shakes the device, alert them if they want a hint
public void onShake()
{
hintAlert.show();
}
});
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
TextView plot; // text view which will hold the plot
plot = (TextView)findViewById(R.id.question1); // look for text called question1 in xml
plot.setMovementMethod(new ScrollingMovementMethod());
AlertDialog.Builder alt_bld = new AlertDialog.Builder(this); // alert dialog box
alt_bld.setMessage("Correct! Proceed to next level?");
alt_bld.setCancelable(false);
alt_bld.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
// if user decides to continue to the next level, load the second easy level
public void onClick(DialogInterface dialog, int id)
{
Intent intent = new Intent(Pictures.this, Pictures.class);
startActivity(intent);
}
});
alt_bld.setNegativeButton("No", new DialogInterface.OnClickListener()
{
// if the user does not want to continue, load the easy mode levels
public void onClick(DialogInterface dialog, int id)
{
Intent intent = new Intent(Pictures.this, Pictures.class);
startActivity(intent);
dialog.cancel();
}
});
final AlertDialog alert = alt_bld.create();
alert.setTitle("Yes! Mano means Hand");
sButton = (Button)findViewById(R.id.ansSubmit1); // submit button will find ansSubmit button in xml
sButton.setOnClickListener(new View.OnClickListener()
{
// if the submit button is clicked check text entered to actual answer
public void onClick(View view)
{
mEdit = (EditText)findViewById(R.id.ansField1);
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
Context context = getApplicationContext();
String text = getResources().getString(R.string.answer1);
// if the text that was entered matches the answer, alert dialog box will appear
if(mEdit.getText().toString().replaceAll(" ", "").replaceAll("-", "").toLowerCase().equals(text))
{
int level = app_preferences.getInt("level", 0);
if (level > 0)
{
level=level-1;
}
level++;
SharedPreferences.Editor editor = app_preferences.edit();
editor.putInt("level", level);
editor.commit();
MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.correct);
mediaPlayer.start();
alert.show();
}
else
{
// if the text that was entered does not match the answer, toast pop up = "Incorrect"
CharSequence message = "Incorrect!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, message, duration);
toast.show(); // show toast alert
v.vibrate(250); // vibrate device for 250ms
}
}
});
}
#Override
protected void onResume()
{
super.onResume();
mSensorManager.registerListener(mSensorListener,
mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_UI);
}
#Override
protected void onPause()
{
mSensorManager.unregisterListener(mSensorListener);
super.onStop();
}
}
public class Pictures<sButton> extends MainActivity
{
int level=0; // integer that will keep track of users progress
Button sButton; // represents the submit button
It appears your class is a Generic of type sButton - and sButton isn't a type.

Application alarm causing a weird error until I press the back button

I have an alarm in my application that notifies me every 10 minutes. It works fine but each time when the alarm notifies me, my application name will show as a box in the middle of the screen, and I can't press anything until I press the back button. It's really weird!
Here is my code:
// Alert Code
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Confirmation");
alertDialog.setMessage("Are you sure you want to send this report?");
run(gotDataS);
// Timer Code
pendingIntent = PendingIntent.getService(CreateNewForm_3.this, 0,
new Intent(NewForm_3.this, MyAlarmService.class), 0);
Send.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
alertDialog.setButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
Toast.makeText(NewForm_3.this, "Sent", 0)
.show();
long firstTime = SystemClock.elapsedRealtime();
am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
firstTime + 10 * 1000, 30 * 1000, pendingIntent);
// firstTime Will be the current_time + ( 10 * 60 * 1000) =)
// 10* 1000 will be (10 * 60 * 1000)
new Handler().postDelayed(new Runnable() {
public void run() {
bCancel.performClick();
}
}, (30 * 1000));
// ( 30 * 1000) will be firstTime + ( 2- duration)
Intent toRecentCases = new Intent(CreateNewForm_3.this,
LMPActivity.class);
startActivity(toRecentCases);
}
});
alertDialog.setButton2("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
// Here you can add functions
}
});
alertDialog.setIcon(android.R.drawable.ic_dialog_alert);
alertDialog.show();
}
});
bCancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
am.cancel(pendingIntent);
}
});
//For Notification -3-
final AlertDialog alertDialog3 = new AlertDialog.Builder(this).create();
alertDialog3.setTitle("Confirmation");
alertDialog3.setMessage("Are you sure you want to quite?");
// Press cancel button it will move user to actvity p
Cancelb.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
alertDialog3.setButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
Intent toRecentCases = new Intent(NewForm_3.this,
LMPActivity.class);
startActivity(toRecentCases);
}
});
alertDialog3.setButton2("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
// Doing nothing!
}
});
alertDialog3.setIcon(android.R.drawable.ic_dialog_alert);
alertDialog3.show();
}
});
}
This is Showing Dialog Activity
public class ShowingDialog extends Activity {
boolean b;
String CancelMsg;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
//For Notification -1-
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Confirmation");
alertDialog.setMessage("Do you really want it?");
// For Notification -2-
final AlertDialog alertDialog2 = new AlertDialog.Builder(this).create();
alertDialog2.setTitle("Confirmation");
alertDialog2.setMessage("Are you sure you want it?");
alertDialog.setButton("yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent= new Intent(ShowingDialog.this,MyPage.class);
startActivity(intent);
;
}
});
alertDialog.setButton2("no",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
alertDialog2.setButton("yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Here you can add functions
// Sending a Message to server that the plaintiff found the case
// For Sending SMS with cancel Request
// Getting Case_ID + putting it inside CancelMsg
CancelMsg = "Case_ID cancel";
if (!b) {
try {
sendSMS("5556", CancelMsg);
Toast.makeText(ShowingDialog.this, "Sent", Toast.LENGTH_LONG)
.show();
} catch (Exception e) {
// TODO Auto-generated catch block
Toast.makeText(ShowingDialog.this, e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}
});
alertDialog2.setButton2("no", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Here you can add functions
// Do nothing
}
});
alertDialog2.setIcon(android.R.drawable.ic_dialog_alert);
alertDialog2.show();
}
});
alertDialog.setIcon(android.R.drawable.ic_dialog_alert);
alertDialog.show();
}
public void sendSMS(String number, String msg) throws Exception {
if (!b) {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(number, null, msg, null, null);
}
b = true;
}
}
In Manifest :
<activity
android:name=".ShowingDialog"
android:theme="#android:style/Theme.Dialog" />
It doesn't appear that you're overloading the back statement, so when you hit the back button you're traveling back up your Back Stack. The Android documentation has more information on this:
Tasks and Back Stack

Showing a dialog box with contents of choosing file and camera

i want to open a dialog box that gives me two option.
1- Choose file from SD Card
2- Take a snapshot from Camera
Right now i am using this code
receipt.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
showDialog(RECEIPT_DIALOG_ID);
}
});
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
AlertDialog.Builder builder = new Builder(this);
case RECEIPT_DIALOG_ID:
builder.setTitle("Choose your file");
dialog = builder.create();
return dialog;
}
Now, how can i add these two options.
Best Regards
Try this it provides both the options
final CharSequence[] items = {"Camera", "Memory Card"};
builder.setTitle(R.string.pic_option);
builder.setIcon(R.drawable.camera_icon);
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
launchCamera(item);
}
});
builder.create();
builder.show();
and the Function launchCamera(item) is here
public void launchCamera(int id){
switch (id) {
case 0:
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
((Activity)getParent()).startActivityForResult(cameraIntent, 1888);
break;
case 1:
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
((Activity)getParent()).startActivityForResult(intent, 2);
break;
default:
break;
}
}
Use this directly in your method.It will show 2 buttons on dialog.
Dialog dialog;
dialog = new Dialog(getParent());
dialog.setContentView(R.layout.camdialog);
dialog.setTitle(" Select the Image");
dialog.setCancelable(true);
sdCard = (Button) dialog.findViewById(R.id.sdCard);
camDialog = (Button) dialog.findViewById(R.id.camDialog);
dialog.show();
dialog.getWindow().setLayout(LayoutParams.FILL_PARENT, 200);
try this...
new AlertDialog.Builder(menu)
.setTitle("Choose your file")
.setMessage("Your msg")
.setPositiveButton("Choose file from SD Card",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
// Your code
}
})
.setNegativeButton("Take a snapshot from Camera",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
//Your code
}
}).show();

Categories

Resources