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(){}
Related
I have this fields where every field is important and I don't have an idea how to do this. Where I want it if I pressed post there will be a message that not all fields have values. Here is my code.
InsertActivity
package com.example.kun.carkila;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.kosalgeek.genasync12.AsyncResponse;
import com.kosalgeek.genasync12.PostResponseAsyncTask;
import java.util.HashMap;
public class InsertActivity extends AppCompatActivity implements View.OnClickListener {
EditText etCarModel,etCarType,etCapacity,etImageURL,etFuelType,etPlateNumber;
Button btnPost;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
etCarModel = (EditText)findViewById(R.id.etCarModel);
etCarType = (EditText)findViewById(R.id.etCarType);
etCapacity = (EditText)findViewById(R.id.etCapacity);
etImageURL = (EditText)findViewById(R.id.etImageURL);
etFuelType = (EditText)findViewById(R.id.etFuelType);
etPlateNumber = (EditText)findViewById(R.id.etPlateNumber);
btnPost = (Button)findViewById(R.id.btnPost);
btnPost.setOnClickListener(this);
}
#Override
public void onClick(View v) {
HashMap postData = new HashMap();
postData.put("txtCarModel",etCarModel.getText().toString());
postData.put("txtCarType",etCarType.getText().toString());
postData.put("txtCapacity",etCapacity.getText().toString());
postData.put("txtImage",etImageURL.getText().toString());
postData.put("txtFuelType",etFuelType.getText().toString());
postData.put("txtPlateNumber",etPlateNumber.getText().toString());
PostResponseAsyncTask taskPost = new PostResponseAsyncTask(InsertActivity.this, postData, new AsyncResponse() {
#Override
public void processFinish(String s) {
if(s.contains("New records created successfully")){
Toast.makeText(InsertActivity.this, "Car Posted!", Toast.LENGTH_SHORT).show();
Intent in = new Intent(InsertActivity.this, ownerhome.class);
startActivity(in);
}else{
}
}
});
taskPost.execute("http://carkila.esy.es/insert.php");
}
}
Hope for a kind response and I wanted to learn in an easy way. Thank you guys.
Before executing your asynctask you have to check is any EdiText feilds are empty or not. Like
TextUtils.isEmpty(etCarModel.getText().toString())
You have to check for each EditText In starting of OnClick method and if any editText is empty then show alert and do not execute your asynktask.
Check first if each field is empty:
#Override
public void onClick(View v) {
HashMap postData = new HashMap();
if (TextUtils.isEmpty(etCarModel.getText().toString())) {
Toast.makeText(this, "Car model is empty", LENGTH_SHORT).show()
return;
}
postData.put("txtCarModel",etCarModel.getText().toString());
if (TextUtils.isEmpty(etCarType.getText().toString())) {
Toast.makeText(this, "Car type is empty", LENGTH_SHORT).show();
return;
}
postData.put("txtCarType",etCarType.getText().toString());
//and so on
}
Yours is a simple problem. I have, because I needed these checks a lot, created a couple of utility methods for this purpose. You may place them in any class that you want.
safeGetText() to get text from a TextView:
public static String safeGetText(TextView textView, boolean isNullable)
{
String result = null;
if(textView != null)
{
CharSequence text = textView.getText();
if(text != null)
{
result = text.toString();
}
}
if(result == null && !isNullable)
{
// This check is for situations where the text cannot be null.
// Now, I find this utterly pointless, but what the hell.
result = "";
}
return result;
}
'isStringNullOrEmpty()' to check for null/empty strings:
public static boolean isStringNullOrEmpty(#Nullable String input)
{
if (input == null || input.length() <= 0)
{
return true;
}
else
{
return false;
}
}
Although these methods don't do anything magical, they helped me clean up the way I checked for Strings in my TextViews.
When you need to check the input (possibly in onClick()), put up empty checks for each field like:
boolean isEmpty = isStringNullOrEmpty(safeGetText(field, true)); // true/false in arg2 doesn't matter here
You would need to apply this check for every field in your current implementation. You could make arrangements to iterate through all fields in a loop like this:
boolean areFieldsValid = true;
for(TextView field : arrayOfAllFields)
{
boolean isCurrentFieldValid = isStringNullOrEmpty(safeGetText(field, true));
areFieldsValid &= isCurrentFieldValid;
}
// Here, the flag 'areFieldsValid' will only be true if all fields are valid
Let me know if this solves your purpose, and/or if you need more help.
You can use an editText array so that you can use a for loop instead of writing it all over. For key name in Hashmap you can use id name of editText in a for loop
String str = editText[i].getResources().getResourceName(id);
str = str.substring(str.lastIndexOf(":id/") + 4);
postData.put(str,editText[i].getText().toString());
This code will be in a for loop to put all the data.
and in similar way you can check where this strings are null or not.
for(int i=0;i<6;i++){
if(editText[i].getText().toString().equals("")){
//Error alert
}
}
I think this will reduce a lot of LOC.
A custom dialog is being used to take in user input, and then these values are being passed to another activity using getter methods.
But when I pass the values to a method that outputs the string values to a CSV file, shipName, analystName etc the values appear as empty in the file like this, " " although I have entered the values in the dialog.
I debugged the problem by watching the String values in the debug menu's expression window, shipName and analystName but the values never update in the expression window.
I gather from this that the method i which the input is being passed over is not correct.
Does anyone know why the values being output are empty?
This the dialog class being used:
package ie.gmi.computing;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.renderscript.Sampler;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MyMessageDialog {
private Context context;
private EditText shipText, scientistNameText , scientistEmailText , volumeText , colourText ;
private String shipString, scientistNameString , scientistEmailString , volumeString , colourString ;
public AlertDialog displayMessage(Context context, String title, String message){
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(title);
builder.setMessage(message);
LayoutInflater inflater = LayoutInflater.from(context);
final View v = inflater.inflate(R.layout.custom_view, null);
builder.setView(v);
shipText = (EditText)v.findViewById(R.id.shipNameEditText);
scientistNameText = (EditText)v.findViewById(R.id.scientistEditText);
scientistEmailText = (EditText)v.findViewById(R.id.emailEditText);
volumeText = (EditText)v.findViewById(R.id.volumeEditText);
colourText = (EditText)v.findViewById(R.id.colourEditText);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog dialog= builder.create();
dialog.show();
Button tb = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
tb.setOnClickListener(new CustomListener(dialog));
return dialog;
}
//getter/setters to allow access to string values
//in SearchResult class
public EditText getShipText() {
return shipText;
}
public void setShipText(EditText shipText) {
this.shipText = shipText;
}
public EditText getScientistNameText() {
return scientistNameText;
}
public void setScientistNameText(EditText scientistNameText) {
this.scientistNameText = scientistNameText;
}
public EditText getScientistEmailText() {
return scientistEmailText;
}
public void setScientistEmailText(EditText scientistEmailText) {
this.scientistEmailText = scientistEmailText;
}
public String getShipString() {
return shipString;
}
public void setShipString(String shipString) {
this.shipString = shipString;
}
public String getScientistNameString() {
return scientistNameString;
}
public void setScientistNameString(String scientistNameString) {
this.scientistNameString = scientistNameString;
}
public String getScientistEmailString() {
return scientistEmailString;
}
public void setScientistEmailString(String scientistEmailString) {
this.scientistEmailString = scientistEmailString;
}
public String getVolumeString() {
return volumeString;
}
public void setVolumeString(String volumeString) {
this.volumeString = volumeString;
}
public String getColourString() {
return colourString;
}
public void setColourString(String colourString) {
this.colourString = colourString;
}
public EditText getVolumeText() {
return volumeText;
}
public void setVolumeText(EditText volumeText) {
this.volumeText = volumeText;
}
public EditText getColourText() {
return colourText;
}
public void setColourText(EditText colourText) {
this.colourText = colourText;
}
#SuppressLint("NewApi")
class CustomListener implements View.OnClickListener {
private final Dialog dialog;
public CustomListener(Dialog dialog) {
this.dialog = dialog;
}
#SuppressLint("NewApi")
#Override
public void onClick(View v) {
if(shipText.getText().toString().isEmpty() && !shipText.getText().toString().equals(null)){
shipText.setError("The Field is required");
}else if(scientistNameText.getText().toString().isEmpty() && !scientistNameText.getText().toString().equals(null)){
scientistNameText.setError("The Field is required");
}else if(scientistEmailText.getText().toString().isEmpty() && !scientistEmailText.getText().toString().equals(null)){
scientistEmailText.setError("The Field is required");
}else if(volumeText.getText().toString().isEmpty() && !volumeText.getText().toString().equals(null)){
volumeText.setError("The Field is required");
}else if(colourText.getText().toString().isEmpty() && !colourText.getText().toString().equals(null)){
colourText.setError("The Field is required");
}else{
shipText.setError(null);
scientistNameText.setError(null);
scientistEmailText.setError(null);
volumeText.setError(null);
colourText.setError(null);
shipString = shipText.getText().toString();
scientistNameString = scientistNameText.getText().toString();
scientistEmailString = scientistEmailText.getText().toString();
volumeString = volumeText.getText().toString();
colourString = colourText.getText().toString();
Toast.makeText(dialog.getContext(), "The Values you get from : " +
"\n Ship name value: " + shipText.getText().toString() +
"\n Scientist name value: " + scientistNameText.getText().toString() +
"\n email value: " + scientistEmailText.getText().toString() +
"\n sample volume value: " + volumeText.getText().toString() +
"\n sample colour value: " + colourText.getText().toString() , Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
}
}
}
And this is how I'm retrieving the values in my SearchResult class, when i select the settings button:
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
MyMessageDialog dialog =new MyMessageDialog();
dialog.displayMessage(SearchResult.this, "Sample Info", "Required");
// store / use the values here
shipName = dialog.getShipString();
analystName = dialog.getScientistNameString();
analystEmail = dialog.getScientistEmailString();
sampleVolume = dialog.getVolumeString();
sampleColour = dialog.getColourString();
longitudeValue = String.valueOf(lng);
latitudeValue = String.valueOf(lat);
sampleMaterial = message;
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Your dialog showing is asynchronous; that is, code execution in onOptionsItemSelected() does not pause after the call to dialog.displayMessage(), so the getters are returning the initial values for those fields, which is null in all cases. You should create an interface that the Activity implements to receive a callback after those fields are set in the onClick() method of your CustomListener, and update the Activity's variables then.
In the dialog class, we create an interface. For example:
public class MyMessageDialog {
public interface DialogCallback {
public void onValuesSet();
}
...
}
Be sure to save a reference to the Context:
public AlertDialog displayMessage(Context context, String title, String message){
this.context = context;
...
}
And at the end of the onClick() method, after the fields' values are set:
((DialogCallback) context).onValuesSet();
The Activity needs to implement the interface we created, the dialog should be a class member, and the fields will be set in the interface's callback method:
public class SearchResult extends Activity
implements MyMessageDialog.DialogCallback {
...
MyMessageDialog dialog;
#Override
public void onValuesSet()
{
shipName = dialog.getShipString();
analystName = dialog.getScientistNameString();
...
}
...
}
Does anyone know why the values being output are empty?
Because all statements from getting data from dialog class is executing after dialog.displayMessage on menu option section.
How to get data from MyMessageDialog on Ok button click ?
1. Instead of getting EditText from MyMessageDialog change all getter/setter method return type to String..
2. Create a event Listener using interface for getting event of Alert close on Ok button click in Activity. you can create event listener as:
Android Custom Event Listener
3. call all setter method on Ok button click of Alert. after calling all setter method call event listener method to execute event in Activity after Alert finish.:
#Override
public void onClick(DialogInterface dialog, int which) {
setShipText(shipText.getText().toString());
setScientistNameText(shipText.getText().toString());
....
//..close alert and call event listener method
}
Your getters don't seem to actually call the getText() method on each EditText view. Modify them do that they do (e.g., scientistNameText.getText()).
PS And, yes, Mike M may indeed write about asyncronicity contributing to the problem. Another approach around that would be to add something like this to the code for each EditText view:
myEditTextView.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
//Set the variable here that you call in your getter. Use `getText()` to get the string (e.g., myGetterVariable = myEditTextView.getText().
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
i finally figured out where to find most of this.
but now i need to know how to test one part of this program for a username.
My goal is if the user doesn't put anything in the program then don't allow anything to continue.
This is a big app. I have like 3 layout files and 3 java files.
Any help would be good if you need me to send the file i can.
package edu.jones.demogamestartarrayadaptor;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
//import android.view.KeyEvent;
import android.view.View;
//import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
//import android.widget.Toast;
public class GameControlMainActivity extends ListActivity
{
//Class-wide variables for data passed/returned
private String userName = "";
//Use an int for gameLevel,naturally...but, this requires
//use of various methods to convert to String and back!
private int gameLevel = 1;
private EditText nameEntryET;
private TextView gameLevelAnnouncerTV;
private TextView gameLevelTV;
Button doneButton;
//This TV prompts user to enter name in the EditText
//Then, it is made invisible
private TextView namePromptTV;
//These two start out invisible and then show the name
private TextView nameSetTV;
private TextView nameEntTV;
//Array of choices for user
static final String[] CHOICES = new String[]
{
"Read directions",
"Play Game",
"Quit"
};
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Set up View ids
nameEntryET = (EditText)findViewById(R.id.enter_nameET);
gameLevelAnnouncerTV = (TextView) findViewById(R.id.game_level_announcer_TV);
gameLevelTV = (TextView) findViewById(R.id.game_level_TV);
//Set the game level in the TextView
gameLevelTV.setText(Integer.toString(gameLevel));
namePromptTV = (TextView)findViewById(R.id.name_prompt_tv);
nameSetTV = (TextView)findViewById(R.id.name_set_tv);
nameEntTV = (TextView)findViewById(R.id.name_entered_tv);
//Set Done button listener to get user's name
doneButton = (Button) findViewById(R.id.doneBtn);
setDoneButtonListener();
//Set up ArrayAdaptor for the options
setListAdapter(new ArrayAdapter<String>
(this, android.R.layout.simple_list_item_1, CHOICES));
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
getListView().setTextFilterEnabled(true);
//Set up the listener for user clicks on the list
setListClickListener();
//this toast is for when it opens
Toast.makeText(this, "yo whats up", Toast.LENGTH_SHORT).show();
}//END onCreate
private void setDoneButtonListener()
{
doneButton.setOnClickListener
(
new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//Get user's name when button is clicked
//Call method to set text and hide button
setUserNameAndHideButton();
}
}
);//END setOnClickListener
}//END setDoneButtonListener
//Sets up username in its TextView, and game level Views,
//then hides the other Views & button
private void setUserNameAndHideButton()
{
userName = nameEntryET.getText().toString();
doneButton.setVisibility(View.GONE);
Toast.makeText(this, "Your name has been entered", Toast.LENGTH_SHORT).show();
//After getting the input, hide the EditText
//VISIBLE(0), INVISIBLE(4) or GONE(8)
nameEntryET.setVisibility(View.INVISIBLE);
namePromptTV.setVisibility(View.GONE);
nameEntTV.setText(userName);
nameSetTV.setVisibility(View.VISIBLE);
nameEntTV.setVisibility(View.VISIBLE);
gameLevelAnnouncerTV.setVisibility(View.VISIBLE);
gameLevelTV.setVisibility(View.VISIBLE);
}//END setUserNameAndHideButton
//Set up the listener for the ListView to interpret user clicks
private void setListClickListener()
{
//Set up the click listener for the options
getListView().setOnItemClickListener
(
new OnItemClickListener()
{
//#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
switch(arg2)
{
case 0: launchDirectionsPage();
break;
case 1: startGame();
break;
case 2: finish();
break;
default: break;
}
}
}//END OnItemClickListener
);//END setOnItemClickListener
}//END setListClickListener
//Launch a simple activity to show a scroll view of directions
protected void launchDirectionsPage()
{
//Set up Intent
Intent launchDirections = new Intent(this, DirectionsPageActivity.class);
startActivity(launchDirections);
}//END launchDirectionsPage
//Launch the activity that allows user to input new game value
//Upon return the onActivityResult method is called
protected void startGame()
{
//Set up Intent to launch other activity: PlayGame
Intent launchGame = new Intent(this, PlayGameActivity.class);
//Info added to the Intent's Bundle to pass to PlayGameActivity
launchGame.putExtra("bdl_username", userName);
launchGame.putExtra("bdl_gamelevel", gameLevel);
startActivityForResult(launchGame, 0);
}//END startGame
//This method will be called when the startGame activity terminates
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == 0 && resultCode == RESULT_OK)
{
//Reset the views to possibly updated info returned in the Intent
//First, access the Bundle's values
userName = data.getExtras().getString("bdl_returnUserName");
gameLevel = data.getExtras().getInt("bdl_returnGameLevel");
//Update the user name & game level with values from other activity
nameEntTV.setText(userName);
gameLevelTV.setText(Integer.toString(gameLevel));
}
}//END onActivityResult
#Override
protected void onSaveInstanceState (Bundle outState)
{
super.onSaveInstanceState(outState);
//Add the username and game level to the Bundle
outState.putString("bdl_savedusername", userName);
outState.putInt("bdl_savedgamelevel", gameLevel);
}//END onSaveInstanceState
#Override
public void onRestoreInstanceState (Bundle savedInstanceState)
{
super.onRestoreInstanceState(savedInstanceState);
//Restore the username and game level from the Bundle
userName = savedInstanceState.getString("bdl_savedusername");
gameLevel = savedInstanceState.getInt("bdl_savedgamelevel");
}//END onRestoreInstanceState
}//END GameControlMainActivity
If you are asking to stop if the username is not entered, just do this:
private void setDoneButtonListener()
{
doneButton.setOnClickListener
(
new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if (nameEntryET.getText().toString().equals("")) {
Toast.makeText(this, "Enter a username", Toast.LENGTH_LONG).show();
} else {
//Get user's name when button is clicked
//Call method to set text and hide button
setUserNameAndHideButton();
}
}
}
);//END setOnClickListener
}//END setDoneButtonListener
if nameEntryET does not have a value entered, nameEntryET.getText().toString() will return an empty string.
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'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;