Store Highest Score and Display It - java

I'm currently learning android app development and on the very beginning phase. I built this game and now i want to set store and display high score as Textview on my screen. I'd really appreciate if anyone could help me out. thanks!
package com.princeghimire.clickmeter;
import android.content.DialogInterface;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity{
TextView tv_time, tv_clicks;
Button b_start, b_click;
CountDownTimer timer;
int time = 10;
int clicks = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setLogo(R.drawable.iconnn);
getSupportActionBar().setDisplayUseLogoEnabled(true);
tv_time = (TextView) findViewById(R.id.tv_time);
tv_clicks = (TextView) findViewById(R.id.tv_clicks);
b_start = (Button) findViewById(R.id.b_start);
b_click = (Button) findViewById(R.id.b_click);
b_start.setEnabled(true);
b_click.setEnabled(false);
timer = new CountDownTimer(10000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
time--;
tv_time.setText("Time: " + time);
}
#Override
public void onFinish() {
b_start.setEnabled(true);
b_click.setEnabled(false);
tv_time.setText("Time: 10" );
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Time's Up Buddy!");
builder.setMessage("Your Score Is: " + clicks);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int which) {
dialogInterface.dismiss();
// finish();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
};
b_click.setOnClickListener(new View.OnClickListener(){
public void onClick (View v){
clicks++;
// switchh.start();
tv_clicks.setText("Your Clicks: " + clicks);
}
});
b_start.setOnClickListener(new View.OnClickListener(){
public void onClick (View v){
timer.start();
b_start.setEnabled(false);
b_click.setEnabled(true);
clicks = 0;
time = 10;
tv_time.setText("Time: " + time);
tv_clicks.setText("Your Clicks: " + clicks);
}
});
}
public void onBackPressed()
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to EXIT?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}

Basically this is the procedure:
Create instance of SharedPreferences and SharedPreferences.Edit SharedPreferences sharedPref = .... AND SharedPreferences.Edit editor = .....
Call this in where your game ends if (sharedPref.getInt("highscore",0) < clicks) { editor.putInt("highscore",clicks).apply() }
The above code will first check the last score you saved in "highscore" key and if your current clicks is higher it will replace it with it, and if this is the first game so the default value will be taken as 0 so the first game's score will be saved as highscore unless its 0 again.
I've made almost the same game, its Taplay and on PlayStore btw.
Good Luck.

You can use SharedPreferences, I suggest you to use Sqlite if you want to keep track of the user game statistics.

Related

How to open a new activity from a dialog fragment

My program opens a DialogFragment class while running in MainActivity.java
I want to be able to click on the "neutral button" of that dialog and open a new activity, SensorDataDisplay.java
I am having trouble finding the right way to reference the Context in my button's onClick.
package com.august.customtisensortagclient;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import java.util.ArrayList;
public class GetInfoDialog extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final String thisWhichGetInfoDialog = ((MainActivity)getActivity()).getWhichGetInfoDialog();
final ArrayList<String> thisScannedDevicesArrayList =
((MainActivity)getActivity()).getScannedDevicesArrayList();
final int thisIsInLeftConnectedDeviceDisplay = ((MainActivity)getActivity()).getIsInLeftConnectedDeviceDisplay();
final int thisIsInRightConnectedDeviceDisplay = ((MainActivity)getActivity()).getIsInRightConnectedDeviceDisplay();
int thisIsInThisConnectedDeviceDisplay = 0;
if (thisWhichGetInfoDialog == "Left") {
thisIsInThisConnectedDeviceDisplay = thisIsInLeftConnectedDeviceDisplay;
} else if (thisWhichGetInfoDialog == "Right")
thisIsInThisConnectedDeviceDisplay = thisIsInRightConnectedDeviceDisplay;
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(thisWhichGetInfoDialog + " Sensor Info");
builder.setMessage("MAC Address: " + thisScannedDevicesArrayList.get(thisIsInThisConnectedDeviceDisplay));
builder.setNeutralButton("View Data", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent myIntent = new Intent(?????, SensorDataDisplay.class);
myIntent.putExtra("key", "TEST VALUE"); //Optional parameters
?????.startActivity(myIntent);
}
});
builder.setNegativeButton("Done", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
return builder.create();
}
}
DialogFragment has getActivity() and getContext() methods (which it inherits from Fragment), both will work in your case. If you're having trouble accessing these methods from the anonymous class (which shouldn't be the case), you can use the GetInfoDialog.this.getActivity() syntax.
getActivity() returns the Activity the fragment is attached to
builder.setNeutralButton("View Data", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent myIntent = new Intent(getActivity(), SensorDataDisplay.class);
myIntent.putExtra("key", "TEST VALUE"); //Optional parameters
getActivity().startActivity(myIntent);
}
});

Save State of a radio button in dialog when ok is pressed and dialog is dismissed

Currently, I have a popup dialogue that shows when I press the currency button, this dialogue contains a set of radio buttons that users can select one of them. I'm trying to get the selected radio button's state to be saved when the user pressed "OK". So that when they press the "Currency" button again, the radio button selection was the one the user chose prior to pressing "OK".
Currently, my code is this:
CurrencyChoiceDialog.java
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.widget.Toast;
public class CurrencyChoiceDialog extends DialogFragment {
final CharSequence[] currencies = {"CAD", "USD", "EURO", "POUNDS"};
String selectedCurrency;
public int selectedElement = -1;
#Override
#NonNull
public Dialog onCreateDialog(Bundle savedInstance){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Choose the default currency").setSingleChoiceItems(currencies, selectedElement, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
switch (i){
case 0:
selectedCurrency = (String)currencies[i];
selectedElement = i;
break;
case 1:
selectedCurrency = (String)currencies[i];
selectedElement = i;
break;
case 2:
selectedCurrency = (String)currencies[i];
selectedElement = i;
break;
case 3:
selectedCurrency = (String)currencies[i];
selectedElement = i;
break;
default:
break;
}
}
}).setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getActivity(), "The chosen currency is: "+ selectedCurrency, Toast.LENGTH_LONG);
}
});
return builder.create();
}
}
Settings.java
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class Settings extends AppCompatActivity implements View.OnClickListener {
Button confirm;
Switch useDefault;
boolean toggle;
private CardView currency;
private CardView tipPercentage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
confirm = findViewById(R.id.saveButton);
useDefault = findViewById(R.id.switch1);
currency = findViewById(R.id.currencyButton);
tipPercentage = findViewById(R.id.tipPercentageButton);
confirm.setOnClickListener(this);
currency.setOnClickListener(this);
tipPercentage.setOnClickListener(this);
final SharedPreferences sharedPreferences = getSharedPreferences("Press", 0);
toggle = sharedPreferences.getBoolean("Switch", false);
useDefault.setChecked(toggle);
useDefault.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
toggle = !toggle;
useDefault.setChecked(toggle);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("Switch", toggle);
editor.apply();
}
});
}
#Override
public void onClick(View view) {
Intent i;
switch (view.getId()) {
case R.id.saveButton:
i = new Intent(this, MainActivity.class);
startActivity(i);
break;
// TODO: Save the state once the OK button is clicked for the currency.
case R.id.currencyButton:
setCurrency(view);
break;
// TODO: Finish implementing the changes in the seekbar and reflecting it with the percentage text, and saving that state in the application
case R.id.tipPercentageButton:
showDialog();
break;
default:
break;
}
}
public void setCurrency(View view) {
CurrencyChoiceDialog currencyChoiceDialog = new CurrencyChoiceDialog();
currencyChoiceDialog.show(getSupportFragmentManager(), "CurrencySelection");
}
public void showDialog() {
final Dialog yourDialog = new Dialog(this);
LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.dialog_tippercentage, (ViewGroup) findViewById(R.id.your_dialog_root_element));
Button yourDialogButton = (Button) layout.findViewById(R.id.your_dialog_button);
SeekBar yourDialogSeekBar = (SeekBar) layout.findViewById(R.id.your_dialog_seekbar);
yourDialog.setContentView(layout);
yourDialog.show();
yourDialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
yourDialog.dismiss();
}
});
}
}
I've tried numerous solutions here but none worked. So any help would be much appreciated. This is my first time trying to make a setting's page for an application. So please make sure your answers are thorough as possible. Thanks in advance.
As I understood the problem, you have to change the variable type of selectedElement from public int to public static int. Furthermore, a quick look to your first listing shows that all switch (i) cases in the function onCreateDialog are applying the same logic, so they are redundant and you can have the same logic by just one case.
Two way to fix this:
Using SharedPreferences: set/get your selectedElement using SharedPreferences
(It will store for long time, after exit from the app also)
OR
Make selectedElement as public static in your in CurrencyChoiceDialog like:
(It will store only when you are on the screen)
public static int selectedElement = -1;
Removed the switch cases and simplified it into one case. As well as had the selectedElement to be static. so it becomes:
public class CurrencyChoiceDialog extends DialogFragment {
final CharSequence[] currencies = {"CAD", "USD", "EURO", "POUNDS"};
String selectedCurrency;
public int selectedElement = -1;
#Override
#NonNull
public Dialog onCreateDialog(Bundle savedInstance){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Choose the default currency").setSingleChoiceItems(currencies, selectedElement, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
selectedCurrency = (String)currencies[i];
selectedElement = i;
}
}).setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getActivity(), "The chosen currency is: "+ selectedCurrency, Toast.LENGTH_LONG);
}
});
return builder.create();
}
}
The -1 in (int cheched) here is the default selected item index (-1 means do not select any default). use this parameter to set the default selected.
AlertDialog.Builder builder=new AlertDialog.Builder(this);
String[] items={"item1","item2"};
SharedPreferences prefs=getPreferences(MODE_PRIVATE);
// If you open the dialog again, we'll put the previously saved option here..
int checked = prefs.getInt("checked", -1);
builder.setTitle("your Title")
.setCancelable(false)
.setSingleChoiceItems(languages, checked , (dialog, which) -{
if (which==0) {
// if selected first item ~ code..
}else if (which==1){
// if selected second item ~ code..
}
// then put your selected item in Shared Preferences to save it..
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("checked",which);
editor.apply();
})
.setNegativeButton(Cancel,null)
.setPositiveButton(OK, (dialog, which) -> {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}

Confirm dialog before exit android studio

Hi guys I have an exit button on my main activity XML however I need it so when the user clicks it, it opens a dialogue to confirm the exit, if yes then exit. if no take them back.
here's my code so far, don't have any of that part however as I don't know where to start.
package com.tradingsoftwarelimited.labelprinter10;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Sets Edit and Data Button to hidden
Button hiddenButton = (Button) findViewById(R.id.editButton);
hiddenButton.setVisibility(View.INVISIBLE);
Button hiddenButton1 = (Button) findViewById(R.id.dataButton);
hiddenButton1.setVisibility(View.INVISIBLE);
//Acknolages settings button
Button showButton = (Button) findViewById(R.id.settingsButton);
//if clicked
showButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//If clicked show Edit and data Button
Button showButton = (Button) (findViewById(R.id.editButton));
showButton.setVisibility(View.VISIBLE);
Button showButton1 = (Button) (findViewById(R.id.dataButton));
showButton1.setVisibility(View.VISIBLE);
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getSupportActionBar().hide();
return true;
}
};
;
private void confirmDialog(Context context){
final AlertDialog alert = new AlertDialog.Builder(
new ContextThemeWrapper(context,android.R.style.Theme_Dialog))
.create();
alert.setTitle("Alert");
alert.setMessage("Do you want to exit ?");
alert.setIcon(R.drawable.warning_icon);
alert.setCancelable(false);
alert.setCanceledOnTouchOutside(false);
alert.setButton(DialogInterface.BUTTON_POSITIVE, "Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alert.dismiss();
finish();
}
});
alert.setButton(DialogInterface.BUTTON_NEGATIVE, "No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alert.dismiss();
}
});
alert.show();
}
Call this method in
#Override
public void onBackPressed() {
super.onBackPressed();
confirmDialog(getApplicationContext());
}
of your Activity
Try like this:
Button exitButton = (Button) findViewById(R.id.exit_button);
exitButton..setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AlertDialog.Builder builde = new AlertDialog.Builder(this);
builde.setMessage(
"Want Exit?")
.setPositiveButton("Yes ", dialogClickListeners)
.setNegativeButton("Cancel", dialogClickListeners).show();
}
});
DialogInterface.OnClickListener dialogClickListeners = new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
switch (which)
{
case DialogInterface.BUTTON_POSITIVE:
finish();
break;
case DialogInterface.BUTTON_NEGATIVE:
break;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Invite = (ImageButton) findViewById(R.id.imageButton5);
final DialogInterface.OnClickListener dialogClickListeners = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
finish();
break;
case DialogInterface.BUTTON_NEGATIVE:
break;
}
}
};
Invite.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AlertDialog.Builder builde = new AlertDialog.Builder(MainActivity.this);
builde.setMessage(
"Want Exit?")
.setPositiveButton("Yes ", dialogClickListeners)
.setNegativeButton("Cancel", dialogClickListeners).show();
}
});
}

buttons work one after the other instead of at the same time [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I am new to programming in java, i'm creating a simple application with multiple buttons within one activity. The problem that I am having is that buttons only work in sequence, one button will carry out its job only after another has been pressed, any help would be appreciated.
Code below:
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// Settings button start
Button settingsButton = (Button) findViewById(R.id.btnSettings);
settingsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startSettings();
}
});
}
public void startSettings() {
Intent launchSettings = new Intent(this, SettingsScreen.class);
startActivity(launchSettings);
// Settings button end
// Set A Button start
Button setAButton = (Button) findViewById(R.id.btnSetA);
setAButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View view) {
setzoneA();
}
});}
public void setzoneA(){
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setMessage("Zone Set");
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(true);
dlgAlert.create().show();
dlgAlert.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//dismiss the dialog
}
});
// Set A Button end
// Set B Button start
Button setBButton = (Button) findViewById(R.id.btnSetB);
setBButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View view) {
setzoneB();
}
});}
public void setzoneB(){
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setMessage("Zone Set");
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(true);
dlgAlert.create().show();
dlgAlert.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//dismiss the dialog
}
});
}
// Set B Button end
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Because you set listeners for button have dependency, All the button initiation and listeners should be in onCreate().
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// Settings button start
Button settingsButton = (Button) findViewById(R.id.btnSettings);
settingsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startSettings();
}
});
Button setAButton = (Button) findViewById(R.id.btnSetA);
setAButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View view) {
setzoneA();
}
});
// Set B Button start
Button setBButton = (Button) findViewById(R.id.btnSetB);
setBButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View view) {
setzoneB();
}
});
}
public void startSettings() {
Intent launchSettings = new Intent(this, SettingsScreen.class);
startActivity(launchSettings);
}
public void setzoneA() {
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setMessage("Zone Set");
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(true);
dlgAlert.create().show();
dlgAlert.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//dismiss the dialog
}
});
}
public void setzoneB() {
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setMessage("Zone Set");
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(true);
dlgAlert.create().show();
dlgAlert.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//dismiss the dialog
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
You need to set all your onClick() listeners within the onCreate() superfunction. Your current solution only sets the listeners when the previous button is clicked.
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// Settings button start
Button settingsButton = (Button) findViewById(R.id.btnSettings);
settingsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startSettings();
}
});
// Set A Button start
Button setAButton = (Button) findViewById(R.id.btnSetA);
setAButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View view) {
setzoneA();
}
});
// Set B Button start
Button setBButton = (Button) findViewById(R.id.btnSetB);
setBButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View view) {
setzoneB();
}
});
}
public void startSettings() {
Intent launchSettings = new Intent(this, SettingsScreen.class);
startActivity(launchSettings);
// Settings button end
}
public void setzoneA(){
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setMessage("Zone Set");
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(true);
dlgAlert.create().show();
dlgAlert.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//dismiss the dialog
}
});
// Set A Button end
}
public void setzoneB(){
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setMessage("Zone Set");
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(true);
dlgAlert.create().show();
dlgAlert.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//dismiss the dialog
}
});
}
// Set B Button end
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

Android Dialog not appearing

I just picked up the android SDK and eclipse and decided to write a simple dialog that pops up when you click a button, however I found out that the showDialog() method has been deprecated and that the DialogFragment was the best way to go about making one, so here it is:
package net.learn2develop.dialog;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.view.View;
import android.widget.Button;
public class DialogWindow extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_window);
Button btn = (Button) findViewById(R.id.btn_dialog);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
class MyDialog extends DialogFragment {
FragmentManager fm = getFragmentManager();
public MyDialog() {
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
//using the builder class
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Simple Dialog")
.setPositiveButton("nothing", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Toast.makeText(getBaseContext(), "ok then", Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Toast.makeText(getBaseContext(), "cancel", Toast.LENGTH_SHORT).show();
}
});
return builder.create();
}
}
MyDialog md = new MyDialog();
md.show(md.fm, "dialog");
}
});
}
}
The Debugger shows the error at:
md.show(md.fm, "dialog");
On further inspection, the fm variable is null according to the variables tab in the debugger, why is this so and is there a more efficient solution to this? I am seriously new to android, sorry if this is an easy question.
You should use an AlertDialog in this case, not a DialogFragment. Here is how I would do it:
public class DialogWindow extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_window);
Button btn = (Button) findViewById(R.id.btn_dialog);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
createDialog.show();
}
});
}
public Dialog createDialog() {
//using the builder class
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Simple Dialog")
.setPositiveButton("nothing", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//getBaseContext() is not advised (I can't remember why right now but I know I read it. You may want to read more that method but for now getActivity will work for your Toast.
//Toast.makeText(getActivity(), "ok then", Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Toast.makeText(getActivity(), "cancel", Toast.LENGTH_SHORT).show();
}
});
return builder.create();
}
}
DialogFragments should be used in conjunction with other Fragments, in the case of a single activity it would be best to use an AlertDialog.

Categories