I'm trying to code a application for andriod (using eclipse) in which when a imagebutton is presses a alertdialouge comes up with a random string from and array, each time the button is pressed i would like it to change the string from the array. I have coded a alertdialouge and some code which gets a random string but it does it to a text-view instead of a alert dialouge. Can you please have a look at my code and tell me what i need to change?
package kevin.erica.box;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import java.util.Random;
public class TheKevinAndEricaBoxActivity extends Activity {
/** Called when the activity is first created. */
private String[] myString;
private String list;
private static final Random rgenerator = new Random();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Resources res = getResources();
myString = res.getStringArray(R.array.myArray);
list = myString[rgenerator.nextInt(myString.length)];
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText(list);
}
public void kevin(View view)
{
new AlertDialog.Builder(this).setTitle("The Box").setMessage(getResources().getText(R.string.list)).setNeutralButton("Close", null).show(); }
}
As I understand, you need to display a randomly selected text string from an array whenever a particular ImageButton is pressed.
Try the following code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Resources res = getResources();
myString = res.getStringArray(R.array.myArray);
list = myString[rgenerator.nextInt(myString.length)];
ImageButton ib = (ImageButton) findViewById(R.id.img_button_id);
ib.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
AlertDialog.Builder b = new AlertDialog.Builder(TheKevinAndEricaBoxActivity.this);
b.setMessage(myString[rgenerator.nextInt(myString.length)]);
Dialog d = b.create();
d.show();
}
});
}
{...
list = myString[rgenerator.nextInt(myString.length)];
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText(list);
}
public void kevin(View view)
{
new AlertDialog.Builder(this).setTitle("The Box").setMessage(getResources().getText(R.string.list)).setNeutralButton("Close", null).show();
}
...}
R.string.list is a static string that will never change during runtime, and it's defined in res/values/strings.xml
I would delete the TextView entirely and pass in the value to be displayed in the alert.
{...
String randomInt = myString[rgenerator.nextInt(myString.length)];
showAlert(randomInt);
}
public void showAlert(String randomInt){
new AlertDialog.Builder(this).setTitle("The Box").setMessage(
"Here's a random number: " + randomInt
).setNeutralButton("Close", null).show();
}
...}
You just need to change either .setTitle(), or .setMessage() to pass in your value. Something like this ought to work for you:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(list)
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// put your code here
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// put your code here
dialog.cancel();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
It is easier to understand what is going on if you don't try to cram all of your chained method calls into one single line.
Also it seems like you got the variable names for these two backwards:
private String[] myString;
private String list;
Related
sry for my english..
In my app from Home_Activity, i click on an Button and a custom AlertDialog shows up. Within this AlertDialog(DialogAdd), i click on an ImageView say iv1 (or ImageButton - both didn't work) and another custom AlertDialog opens(Choose) - so far so good. Now i have my 2nd AlertDialog opened and see, say 4 little pictures. When i click on one of these pictures, the second AlertDialog should close and the ImageView (iv1) should change to that choosen icon from AlertDialog 2. I got everything running but not to change this ImageView/ImageButton...
I seperated this behaviour into a little app..
Home_Activity
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Home_Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.btn_showDialog);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogAdd addEntrieActivity = new DialogAdd(Home_Activity.this);
addEntrieActivity.createDialogAdd(Home_Activity.this);
}
});
}
}
DialogAdd
import android.content.Context;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
public class DialogAdd implements View.OnClickListener, Choose.Choose_Interface {
private LayoutInflater inflater;
private View view;
private Context context;
private AlertDialog dialog;
private String selectetSmile = null;
private ImageView ib_dialog_smile;
public DialogAdd(final Context context) {
this.context = context;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.dialog_line, null);
ib_dialog_smile = (ImageView) view.findViewById(R.id.ib_dialog_smile);
ib_dialog_smile.setOnClickListener(this);
}
public void createDialogAdd(Context context) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
builder.setView(view);
dialog = builder.create();
dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
dialog.show();
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.ib_dialog_smile){
Choose choose = new Choose(context);
choose.createDialogChoose();
}
}
#Override
public void selectedSmile(String smile) {
selectetSmile = smile;
if(selectetSmile.equals("oh")){
ib_dialog_smile.setImageResource(R.drawable.oh);
}else if(selectetSmile.equals("oh_nooo")){
ib_dialog_smile.setImageResource(R.drawable.oh_nooo);
}else if(selectetSmile.equals("oh_what")){
ib_dialog_smile.setImageResource(R.drawable.oh_what);
}else if(selectetSmile.equals("oh_yes")){
ib_dialog_smile.setImageResource(R.drawable.oh_yes);
}
}
}
Choose
public class Choose {
public interface Choose_Interface {
void selectedSmile(String flag);
}
public Choose_Interface mCallback;
private View view;
private Context context;
private LayoutInflater inflater;
private AlertDialog dialog;
private ImageView oh, oh_nooo, oh_what, oh_yes;
public Choose(final Context context) {
this.context = context;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.choose, null);
mCallback = new DialogAdd(context);
oh = (ImageView) view.findViewById(R.id.oh);
oh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCallback.selectedSmile("oh");
Toast.makeText(context, "oh klicked", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
oh_nooo = (ImageView) view.findViewById(R.id.oh_nooo);
oh_nooo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCallback.selectedSmile("oh_nooo");
Toast.makeText(context, "oh_nooo klicked", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
oh_what = (ImageView) view.findViewById(R.id.oh_what);
oh_what.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCallback.selectedSmile("oh_what");
Toast.makeText(context, "oh_what klicked", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
oh_yes = (ImageView) view.findViewById(R.id.oh_yes);
oh_yes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCallback.selectedSmile("oh_yes");
Toast.makeText(context, "oh_yes klicked", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
}
public void createDialogChoose() {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
builder.setView(view);
dialog = builder.create();
dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
dialog.show();
}
}
i've tried it with invalidate ib_dialog_smile, i used an ImageButton and also ImageView, AppCompatImageView, setImageDrawable, setImageResource.. but the image didnt get updated.
Can someone please help me out to change ib_dialog_smile image?
Thank you!
I think your code is a little complicated. You don't need seperate classes to create two custom AlertDialogs. Just create two XML layouts each for every dialog and style them the way you want (in the first XML layout put your "chosen" ImageView and the button and in the second the four images).
Let's call them layout_1 (chosen icon) and layout_2 (four options)
then in your home_activity inflate those in a view var and choose them as alertDialog views like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Creating the first dialog.
AlertDialog.Builder dialogOneBuilder = new AlertDialog.Builder(this);
View layout1 = getLayoutInflater().inflate(R.id.layout_1, null);
dialogOneBuilder.setView(layout1)
AlertDialog dialogOne = dialogOneBuilder.show();
//Finding the chosen icon and button image from dialog 1
final ImageView chosenIcon = (ImageView)layout1.findViewById(R.id.chosen_icon);
Button chooseButton = (Button)layout1.findViewById(R.id.choose_button);
//On button click
chooseButton.setOnClickListener(new View.OnClickListener(){
//Creating the second dialog.
AlertDialog.Builder dialogTwoBuilder = new AlertDialog.Builder(this);
View layout2 = getLayoutInflater().inflate(R.id.layout_2, null);
dialogTwoBuilder.setView(layout2)
AlertDialog dialogTwo = dialogTwoBuilder.show();
//finding the ImageViews of the four choices
ImageView img1 = (ImageView)layout2.findViewById(R.id.img1);
ImageView img2 = (ImageView)layout2.findViewById(R.id.img2);
ImageView img3 = (ImageView)layout2.findViewById(R.id.img3);
ImageView img4 = (ImageView)layout2.findViewById(R.id.img4);
//Add them in a LinkedList helps to shrink your code
LinkedList<ImageView> choices = new LinkedList<>();
choices.add(img1);
choices.add(img2);
choices.add(img3);
choices.add(img4);
//Now set ONE ClickListener for all choices
for(int i = 0; i < choices.size(); i++){
choices.get(i).setOnClickListener(new View.OnClickListener(){
//change your icon to the chosen image
chosenIcon.setImageDrawable(choices.get(i).getDrawable());
//And close the second dialog.
dialogTwo.dismiss();
});
}
});
}
Worked perfectly for my voting & commenting dialog. Hope this helped you and the code was readable.
The original code has been deleted, the new working code is shown. The idea behind the code is to create a new textView within a layout that has a custom name to it that the user provides. Previously, a NPE error was happening. This is a fix. Any questions, please feel free to ask.
EDIT: Found the solution
The fix needs to be as followed:
accountEdit = new EditText(this); // accountEdit needs to be a global variable
then within the builder.setPositiveButton
builder.setPositiveButton(R.string.btn_save, new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dInterface, int whichButton)
{
LinearLayout lineLayout = (LinearLayout)findViewById(R.id.linear_layout);
String newAccountName = accountEdit.getText().toString();
newTextView = new TextView( getBaseContext() );
newTextView.setVisibility(View.VISIBLE);
newTextView.setText( newAccountName );
newTextView.setId(id);
newTextView.setTextSize(35);
newTextView.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onClickNew(view);
}
});
newTextView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
Toast.makeText(getBaseContext(), "Testing" , Toast.LENGTH_LONG).show();
return true;
}
});
This will create the button, as well as set the name of the button to the information that is in the EditText within the Dialog Box. Previously, the EditText was from another activity, and was being called wrong, which caused the NPE. Thank you for all the help.
As Wenhui metioned, you call the finViewById inside the onclick listener of the button, so the wrong context is used. Do it like in the following example:
final EditText accountEdit = (EditText)findViewById(R.id.newAccountButton);
final String newAccountName = accountEdit.getText().toString();
final LinearLayout lineLayout = (LinearLayout)findViewById(R.id.linear_layout);
builder.setPositiveButton(R.string.btn_save, new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dInterface, int whichButton)
{
newTextView = new TextView(getBaseContext());
newTextView.setVisibility(View.VISIBLE);
newTextView.setText("Test");
newTextView.setId(id);
newTextView.setTextSize(35);
newTextView.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onClickNew(view);
}
});
lineLayout.addView(newTextView);
id++;
}
});
I have created 2 classes and one Interface. One Interface that handles dialog clicks,a MainActivity class that hold a button and a textView. The MainActiviy class instantiates my second class(FireMissilesFragment) which contains an AlertDialog as a fragment. In the FireMisslesFragment I have dynamically created EditText. The problem with my app is that when I call (onsavenstancestate) in my mainActivity class in which FireMissilesFragment is instantiated in, i try to save my editText values so that when the popup closes and I restart it, the values of editText will maintain it's values once the popup opens again.
I have tried (onSaveInstanceState) method and the values hold;however, it is yet possible for me to recreate what was destroyed once the dialog is initiated again.Can Someone please shed some light on this matter.
Here is my code:
//===============================Interface=====================================//
public interface NoticeDialogListener {
public void onDialogPositiveClick(DialogFragment dialog,EditText[] editText);
public void onDialogNegativeClick(DialogFragment dialog);
}
//==========================MainActivity Class=============================//
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends FragmentActivity implements ` NoticeDialogListener{
private EditText[] _edText;
private TextView _tv;
private Multiplication multi;
private Double[] s;
private String s1;
public static final String _SCORE1 = "score1";
public static final String _SCORE2 = "score2";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_tv = (TextView)findViewById(R.id.textView1);
Button dAction = (Button)findViewById(R.id.button1);
s = new Double[2];
dAction.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {//open();
confirmFireMissiles();
}
});//ssetOnclickLi...
///success thank god.
//===================================================//
}
public void confirmFireMissiles() {
DialogFragment newFragment = new FireMissilesDialogFragment();
newFragment.show(getSupportFragmentManager(),"ff");
}//confirmFireMisslesClosing brace
// The below is what happens when the Button "multiply" in
Dialog window pops up.
#Override
public void onDialogPositiveClick(DialogFragment dialog,EditText[]
editText) {
_edText = editText; // is this association
multi = new Multiplication();
try{
// gets the text and stores to string array.
s[0]=Double.parseDouble(_edText[0].getText().toString());
s[1]=Double.parseDouble(_edText[0].getText().toString());
Log.d("hello", String.valueOf(s[0]));
}catch(NumberFormatException e){
_tv.setText("please Insert an Number and calculate again"); //
Log.d("Error", "place in numbers please");
}
s1 = String.valueOf(multi.multiply(s[0],s[1]));
//set Textview to s1.
_tv.setText(s1);
}
#Override
public void onDialogNegativeClick(DialogFragment dialog) {}
}
//================================================================================//
public class FireMissilesDialogFragment extends DialogFragment {
private AlertDialog.Builder builder;
private EditText[] _edText; // enable when ready
private NoticeDialogListener _mListener;
public static final String _SCORE1 = "score1";
public static final String _SCORE2 = "score2";
private Double[] s;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
builder = new AlertDialog.Builder(getActivity());
//shows added content to dialog.
// d = new String[2];
s = new Double[2];
if(savedInstanceState !=null){
s[0] = Double.parseDouble(savedInstanceState.getString(_SCORE1));
s[1] = Double.parseDouble(savedInstanceState.getString(_SCORE2));
Log.d("Hey",String.valueOf(s[0]));
_edText[0].setText(String.valueOf(s[0]));
showIt();
}else{
showIt();
}
//sets the characterisitcs of the dialogue.
builder.setTitle("We are all stars of the show.");
builder.setMessage( "we are strong")
.setPositiveButton("Multiply", new
DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id) {
// enable when ready
_mListener.onDialogPositiveClick(FireMissilesDialogFragment.this,_edText);
}
});
// Create the AlertDialog object and return it
return builder.create();
}
public void showIt(){
// This piece of code creates a Linear layout that is suppose to show in a dialogue popup.
LayoutParams param = new
LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT, 1.0f);
LinearLayout layout= new LinearLayout(getActivity());
layout.setLayoutParams(param);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setBackgroundColor(Color.BLACK);
// Dynamically place EditText efficiently Inside Linear Layout.
_edText = new EditText[4];
for (int i = 0;i< _edText.length;i++) {
_edText[i] = new EditText(getActivity());
_edText[i].setInputType(InputType.TYPE_CLASS_NUMBER |
InputType.TYPE_NUMBER_FLAG_DECIMAL);
_edText[i].setTextSize(20)
try{
s[i] =Double.parseDouble(
_edText[i].getText().toString());
}catch(NumberFormatException e){
// Log.d("hello", "wrong input");
}
layout.addView(_edText[i]);
}
builder.setView(layout);
}
//============================================== Look over this code======////////////
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
//Verify that the host activity implements the callback interface
try {
// Instantiate the NoticeDialogListener so we can send events to the host
_mListener = (NoticeDialogListener) activity;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(activity.toString()
+ " must implement NoticeDialogListener");
}
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putDouble(_SCORE1,s[0]);
savedInstanceState.putDouble(_SCORE2,s[1]);
super.onSaveInstanceState(savedInstanceState);
}
}
You could probably use SharedPreferences and store the information there, and then set the text of the text edit to the result of the shared preferences? or did I get the whole idea wrong?
here is an example of a simple save function:
SharedPrefrences scores = getSharedPreferences("key_name_here", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = scores.edit();
editor.putInt("key1", key1Var);
editor.putInt("key2", key2Var);
editor.commit();
and to retrive:
Var = getPrefrences(Context.MODE_PRIVATE).getInt("key1",default value);
That should probably do the trick
i am new to developing apps for android and i want to create a simple Conterter app, just for the start. In my view i have a edittext and a Button. If i click the button, it will open a AlertDialog with list of strings. I cant figure out how to manage this: When i click on one item in the AlertView i want to set the text of the button to the selected string and dismiss the AlertDialog. Can somebody please help me ?
public class VypocetDlzkyActivity extends Activity {
EditText HodnotaDlzka;
Button prevodDlzkaZtlacidlo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vypocet_dlzky);
}
public void zmenPrevodZ(View view){
final String[] jednotkyDlzky = {"milimeter", "centimeter", "decimeter", "meter", "kilometer", "svetelny rok"};
AlertDialog.Builder builder = new AlertDialog.Builder(VypocetDlzkyActivity.this);
builder.setTitle("Vyberte jednotku");
builder.setItems(jednotkyDlzky,null);
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
String value = jednotkyDlzky[item].toString();
prevodDlzkaZtlacidlo.setText(value);
dialog.cancel();
}
};
final AlertDialog alert = builder.create();
alert.show();
}
You need to set the values of these 2 member variables in your onCreate() method, like this:
HodnotaDlzka = (EditText)findViewById(R.id.xxxx);
prevodDlzkaZtlacidlo = (Button)findViewById(R.id.yyyy);
xxxx is the ID you gave the EditText in activity_vypocet_dlzky.xml and yyyy is the ID you gave to the Button.
Also, after a button is clicked in the AlertDialog, the dialog is automatically dismissed, so you don't need to call dialog.cancel().
Problem is you didnt add any onClick listnerz.On clicking on button you need to call the required method.
public class MainActivity extends Activity implements OnClickListener {
EditText HodnotaDlzka;
Button prevodDlzkaZtlacidlo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HodnotaDlzka = (EditText) findViewById(R.id.e1);
prevodDlzkaZtlacidlo = (Button) findViewById(R.id.b1);
prevodDlzkaZtlacidlo.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
final String[] jednotkyDlzky = {"milimeter", "centimeter", "decimeter", "meter", "kilometer", "svetelny rok"};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Vyberte jednotku");
builder.setItems(jednotkyDlzky,new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
String value = jednotkyDlzky[item].toString();
prevodDlzkaZtlacidlo.setText(value);
}
});
enter code here
final AlertDialog alert = builder.create();
alert.show();
}
}
So im sure this is probably a fairly easy question but I am stumped because I am a beginner.
I am looking to pass a value from one class to another, and I have my helper function down and working just fine. If i create an integer outside of my onClick I can pass it no problem. If I create it inside the onClick though it doesn't seem to make it out.
package com.movi.easypar;
//import java.util.logging.Handler;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class EntryScreen extends Activity implements OnClickListener {
Button buttonSetHoles, buttonSetPlayers, buttonLetsGo;
TextView textGameSetup;
public int setHoles; <--- declared here###############################
private String name1 = "Crista";
private String name2 = "Rob";
private String name3 = "Gato";
private String name4 = "Movi";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.entryscreen);
//******************//
//***DEFINE FONTS***//
//******************//
Typeface merge = Typeface.createFromAsset(getAssets(), "merge.otf");
//*****************************************************//
//***CREATES THE UI FOR EACH OF THESE IN JAVA MEMORY***//
//*****************************************************//
buttonSetHoles = (Button)findViewById(R.id.buttonSetHoles);
buttonSetPlayers = (Button)findViewById(R.id.buttonSetPlayers);
buttonLetsGo = (Button)findViewById(R.id.buttonLetsGo);
textGameSetup = (TextView)findViewById(R.id.textGameSetup);
buttonSetHoles.setTypeface(merge);
buttonSetPlayers.setTypeface(merge);
buttonLetsGo.setTypeface(merge);
textGameSetup.setTypeface(merge);
buttonSetHoles.setText("Set Holes");
buttonLetsGo.setText("Lets Go");
buttonSetPlayers.setText("Set Players");
//******************************//
//***DEFINES BUTTON LISTENERS***//
//******************************//
buttonSetHoles.setOnClickListener(this);
buttonSetPlayers.setOnClickListener(this);
buttonLetsGo.setOnClickListener(this);
}
//*************************************************//
//***SETS ON CLICK FUNCTIONALITY FOR ALL BUTTONS***//
//*************************************************//
#Override
public void onClick(View src) {
switch(src.getId()){
case R.id.buttonSetPlayers:
break;
case R.id.buttonSetHoles:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final CharSequence[] items = {"18", "9"};
builder.setTitle("Set Holes");
builder.setItems(items, new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialogInterface, int item) {
Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
if (items[item].equals("9")){
EntryScreen.this.setHoles = 9; <---#### VALUE SET HERE ####
}
else if (items[item].equals("18")){
EntryScreen.this.setHoles = 18;
}
return;
}
});
builder.create().show();
return;
case R.id.buttonLetsGo:
//*********************************//
//***LAUNCHES ACTUAL APPLICATION***//
//*********************************//
TranslateAnimation slide = new TranslateAnimation(0, -500, 0,0 );
slide.setDuration(1000);
slide.setFillAfter(true);
buttonLetsGo.startAnimation(slide);
buttonSetPlayers.startAnimation(slide);
buttonSetHoles.startAnimation(slide);
Intent myIntent = new Intent(src.getContext(), EasyPar.class);
startActivityForResult(myIntent, 0);
break;
}
EntryScreen.this.finish();
}
public String getNames() {
return name1;
}
public void setNames(String playerName1) {
name1 = playerName1;
}
public int getHoles() {
return setHoles; <---- #### THIS DOES NOT SEE VALUE SET IN ONCLICK ####
}
}
This helper does not seem to be able to see the setHoles value that is created onClick.
Any suggestions? Thanks in advance!
It's a scope thing. A variable defined in a function has local scope, and will be destroyed when the function returns. You need a field to hold your value if you wish to retain it.
[EDIT]
Then allow me to elaborate. You can create a field by typing the following line outside a function, inside the class:
[Access][Type][Name];
ex:
class foo{
public int dice;
public void onClick(){
//now the dice's value is saved throught the lifecycle of the Activity
}
}
[EDIT]
I copied your code and ran it. (Modified just a little.)
public class Main extends Activity implements OnClickListener {
Button buttonSetHoles, buttonSetPlayers, buttonLetsGo;
TextView textGameSetup;
public int setHoles; //<--- declared here###############################
private String name1 = "Crista";
private String name2 = "Rob";
private String name3 = "Gato";
private String name4 = "Movi";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//******************//
//***DEFINE FONTS***//
//******************//
Typeface merge = Typeface.createFromAsset(getAssets(), "merge.otf");
//*****************************************************//
//***CREATES THE UI FOR EACH OF THESE IN JAVA MEMORY***//
//*****************************************************//
/*
buttonSetPlayers = (Button)findViewById(R.id.buttonSetPlayers);
buttonLetsGo = (Button)findViewById(R.id.buttonLetsGo);
textGameSetup = (TextView)findViewById(R.id.textGameSetup);
*/
buttonSetHoles = (Button) findViewById(R.id.buttonSetHoles);
/*
buttonSetHoles.setTypeface(merge);
buttonSetPlayers.setTypeface(merge);
buttonLetsGo.setTypeface(merge);
textGameSetup.setTypeface(merge);
buttonSetHoles.setText("Set Holes");
buttonLetsGo.setText("Lets Go");
buttonSetPlayers.setText("Set Players");
*/
//******************************//
//***DEFINES BUTTON LISTENERS***//
//******************************//.
buttonSetHoles.setOnClickListener(this);
/*
buttonSetPlayers.setOnClickListener(this);
buttonLetsGo.setOnClickListener(this);
*/
}
//*************************************************//
//***SETS ON CLICK FUNCTIONALITY FOR ALL BUTTONS***//
//*************************************************//
#Override
public void onClick(View src) {
switch (src.getId()) {
case R.id.buttonSetHoles:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final CharSequence[] items = { "18", "9" };
builder.setTitle("Set Holes");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int item) {
Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
if (items[item].equals("9")) {
setHoles = 9;// <---#### VALUE SET HERE ####
Toast.makeText(Main.this, "getHoles()=" + getHoles(), Toast.LENGTH_SHORT);
}
else if (items[item].equals("18")) {
setHoles = 18;
Toast.makeText(Main.this, "getHoles()=" + getHoles(), Toast.LENGTH_SHORT);
}
return;
}
});
builder.create().show();
return;
}
//finish();
}
public String getNames() {
return name1;
}
public void setNames(String playerName1) {
name1 = playerName1;
}
public int getHoles() {
return setHoles;
}
}
And it seems to work just fine.
If you declare the variable inside the method, an external method is surely not able to see it, it's not in the same scope, you can still declare it outside and then set a value from inside the onClick() method.
Declare it as public/private variable outside the methods.
are you sure your setHoles is even being set? to 9 or 18? try adding a println(setHoles) in your onclick to ensure that the value is being set properly. Also, you are declaring your setHoles variable outside of onCreate but within the same class as getHoles() and onClick() right?
when you compare Strings always use equal method.
like:
if (items[item].equals( "9")){
}
and i prefer to user Setters and Getters on variables:
setHoles(int value){}
and
int getHoles(){}