Custom Dialog with game score android - java

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.

Related

Alert Dialog Button Pressed returning 0 values always

So, I want to detect button pressed by the user when an alert dialog pops up. This is my code.
public class AlertUtils {
private int BTN_PRESSED;
private AlertDialog.Builder builder;
public AlertUtils(Context context){
builder = new AlertDialog.Builder(context);
}
public int ShowAlertWithTwoButtons(String Title,String Message,String PositiveButtonText,
String NegativeButtonText){
builder.setTitle(Title);
builder.setMessage(Message);
builder.setPositiveButton(PositiveButtonText, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
BTN_PRESSED = i;
}
});
builder.setNegativeButton(NegativeButtonText, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
BTN_PRESSED = i;
dialogInterface.dismiss();
}
});
builder.show();
return BTN_PRESSED;
}
}
By calling ShowAlertWithTwoButtons method, returns int value detecting Positive or Negative Button pressed. My Problem is it's giving me default 0 value when I chose from an alert dialog and when I again open us alert dialog it returns the correct value.
Try in this way. Make AlertUtils class like this.
public class AlertUtils {
private AlertDialog.Builder builder;
private AlertDialogListener alertDialogListener;
// Interface to send back the response of click
interface AlertDialogListener {
void onClick(int a);
}
public AlertUtils(Context context, AlertDialogListener alertDialogListener) {
builder = new AlertDialog.Builder(context);
this.alertDialogListener = alertDialogListener;
}
public void ShowAlertWithTwoButtons(String Title, String Message, String PositiveButtonText,
String NegativeButtonText) {
builder.setTitle(Title);
builder.setMessage(Message);
builder.setPositiveButton(PositiveButtonText, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// if you want to pass the actual value of i,then pass the i in onClick or if you want 1 on
// positive button click then pass 1 here.
alertDialogListener.onClick(1);
}
});
builder.setNegativeButton(NegativeButtonText, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// if you want to pass the actual value of i, then pass the i in onClick or if you want 1 on
// negative button click then pass 0 here.
alertDialogListener.onClick(0);
dialogInterface.dismiss();
}
});
builder.show();
}
}
Call the dialog in this way where you need this.
AlertUtils alertUtils = new AlertUtils(getContext(), new AlertUtils.AlertDialogListener() {
#Override
public void onClick(int a) {
if (a == 1) {
// Do your work on Positive button click
} else {
// Do your work on Negative button click
}
}
});
alertUtils.ShowAlertWithTwoButtons("Alert Dialog", "Alert Dialog Description ", "Positive", "Negative");
You'll always get BTN_PRESSED with 0 value whenever you're instantiating your AlertUtils object and the calling the ShowAlertWithTwoButtons method. But you'll get another value if you're recalling the ShowAlertWithTwoButtons again.
I think what you're currently doing is like the following:
// First, you're instantiating the object
AlertUtils alertUtils = new AlertUtils(getContext());
// then you're calling the method
int pressedButton = alertUtils.ShowAlertWithTwoButtons("title", "message", "yes", "no");
// which will return pressedButton as 0
// then you calling the method again after clicked yes or no
int anotherPressedButton = alertUtils.ShowAlertWithTwoButtons("title", "message", "yes", "no");
// which will not zero. But can be -1, -2, -3 like in the
// https://developer.android.com/reference/android/content/DialogInterface.html
Which is incorrect if want to get the button value directly after the click because of asynchronous nature of AlertDialog interface.
Instead, you need to add a listener (ohh no, another listener) to your AlertUtils.
UPDATE
You need to add another listener for click button, something like this:
public class AlertUtils {
public interface Listener {
void onButtonClicked(int pressedButton);
}
private Listener mListener;
private AlertDialog.Builder builder;
public AlertUtils(Context context, Listener listener){
builder = new AlertDialog.Builder(context);
mListener = listener;
}
public void ShowAlertWithTwoButtons(String Title,String Message,String PositiveButtonText,
String NegativeButtonText){
...
builder.setPositiveButton(PositiveButtonText, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
mListener.onButtonClicked(i);
}
});
builder.setNegativeButton(NegativeButtonText, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
mListener.onButtonClicked(i);
dialogInterface.dismiss();
}
});
builder.show();
}
}
then you can create and call the method with:
// create the listener to listen for the clicked button.
AlertUtils.Listener listener = new AlertUtils.Listener() {
#Override
public void onButtonClicked(int pressedButton) {
// here you'll receive the button value
// do something here.
}
};
AlertUtils alertUtils = new AlertUtils(getContext(), listener);
// then you're calling the method
alertUtils.ShowAlertWithTwoButtons("title", "message", "yes", "no");

How to make AlertDialog view in Input method Service?

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. :)

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.

Execution doesn't wait to Alertdialog.dismiss()

I'm developing an Android application and I have this question:
How can I do to make execution waits until user has selected an option from an AlertDialog?
This is my code:
if (mPerson== null)
{
mPerson = new Person();
AlertDialog dialog = null;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(getString(R.string.dialog_message_select))
.setTitle(getString(R.string.dialog_title_attention));
builder.setPositiveButton(R.string.male, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
mPerson.setGender(Gender.male);
dialog.dismiss();
}
});
builder.setNegativeButton(R.string.female, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int arg1)
{
mPerson.setGender(Gender.female);
dialog.dismiss();
}
});
dialog = builder.create();
dialog.show();
}
// TODO: Show data.
getWidgetsRefereces();
customizeLayout();
loadSpinnerValues();
After dialog.dismiss() I have to execute this:
// TODO: Show data.
getWidgetsRefereces();
customizeLayout();
loadSpinnerValues();
Do the following:
AlertDialog dialog = null;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(getString(R.string.dialog_message_select))
.setTitle(getString(R.string.dialog_title_attention));
builder.setPositiveButton(R.string.male, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
mPerson.setGender(Gender.male);
dialog.dismiss();
postSelection();
}
});
builder.setNegativeButton(R.string.female, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int arg1)
{
mPerson.setGender(Gender.female);
dialog.dismiss();
postSelection();
}
});
dialog = builder.create();
dialog.show();
}
Call this method once the selection is complete.
public void postSelection(){
getWidgetsRefereces();
customizeLayout();
loadSpinnerValues();
}
Think in terms of event based execution. If you want some code to execute when you press a button, then wire it to do so. Place the code in question in a method that you can call whenever you want.
Generally, when you are programming on Android, you need to adhere to the event based nature of the platform. Traditional procedural sequential thinking will lead you to dead ends.
You have to customize your dialog interface like this .
You should use onDismissListener on dialog interface.Dont make it anonymous.
private class MyDialogInterfaceMethod implements DialogInterface.OnClickListener,DialogInterface.OnDismissListener
{
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
//when user click a button
}
#Override
public void onDismiss(DialogInterface dialog) {
// TODO Auto-generated method stub
//put your code here
}
}
Than use it on your alert dialog like this
builder.setNegativeButton("CANCEL",new MyDialogInterfaceMethod ());

How to refresh a listview in Android?

I'm using this pieces of code, in the activity:
public void carregaListaDemanda(){
setContentView(R.layout.listaviewdemanda);
lstDem = (ListView) findViewById(R.id.listViewDemanda);
DemandaAdapter adapter = new DemandaAdapter(ctx,
bancodedados.getAllDem(), this);
lstDem.setAdapter(adapter);
lstDem.setItemsCanFocus(true);
teste=0;
}
and in the adapter:
public void onClick(View v) {
AlertDialog alertDialog = new AlertDialog.Builder(ctx).create();
alertDialog.setTitle("Do you wanna delete?");
alertDialog.setIcon(R.drawable.icon);
alertDialog.setMessage("if 'yes' the demand '"
+ dem.getNr_demanda() + "' will be deleted!");
alertDialog.setButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
// if yes delete, and REFRESH the screen
DemandaDAO dbHelper;
try {
dbHelper = new DemandaDAO(ctx);
dbHelper.DeleteDem(dem);
} catch (FileNotFoundException e) {
e.printStackTrace();
}}
});
alertDialog.setButton2("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
return;
}
});
alertDialog.show();
}
});
I want to refresh the listview after deleting a demand, but it results in a forceclose if I call the method in activity again.
call adapter.notifyDataSetChanged() , it Notifies the attached View that the underlying data has been changed and it should refresh itself.

Categories

Resources