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.
Related
I am doing a multiscreen quiz app. For each question I have a separate activity / screen. At the bottom of each screen there are next/previous "buttons" which navigate to the next/previous screen. Please see the UI example of a screen with a question:
I have a problem though. Let's assume a user selects answers to a question 2 and then clicks "Previous", selects an answer in question 1 and hits "Next".
I would like to save the UI state of the Question 2, so the selected answer stays if a user comes back to a question either by clicking previous or next.
One thing I managed to accomplish is when a user clicks "previous" the UI stays, I used the following code in the manifest file:
android:launchMode="singleTask"
However I cannot make it saved when a user comes bak to a question via "next". Here is my code for the activity with the question 2:
package com.example.justynagolawska.quizappiteration2;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
public class Question2Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question2);
ActionBar actionbar = getSupportActionBar();
// Applies the custom action bar style
getSupportActionBar().setDisplayOptions(actionbar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.action_bar);
// Changes the action bar title
TextView title = (TextView) getSupportActionBar().getCustomView().findViewById(R.id.action_bar_title);
title.setText(R.string.q2_name);
//Getting the intent with score for question 1
Intent question2Intent = getIntent();
final int resultQ1 = question2Intent.getIntExtra("q1result", 0);
// Find the View that shows the next TextView
TextView nextQuestion = (TextView) findViewById(R.id.next);
// Set a click listener on that View
nextQuestion.setOnClickListener(new View.OnClickListener() {
// The code in this method will be executed when next View is clicked on.
#Override
public void onClick(View view) {
//Getting the answer to question 2 checkbox 1
CheckBox checkBox1Q2 = (CheckBox) findViewById(R.id.checkbox1Q2);
boolean isCheckBox1Q2 = checkBox1Q2.isChecked();
//Getting the answer to question 2 checkbox 2
CheckBox checkBox2Q2 = (CheckBox) findViewById(R.id.checkbox2Q2);
boolean isCheckBox2Q2 = checkBox2Q2.isChecked();
//Getting the answer to question 2 checkbox 3
CheckBox checkBox3Q2 = (CheckBox) findViewById(R.id.checkbox3Q2);
boolean isCheckBox3Q2 = checkBox3Q2.isChecked();
//Calculate Question 2 score
int resultQ2 = calculateResultQ2(isCheckBox1Q2, isCheckBox2Q2, isCheckBox3Q2);
Intent question3Intent = new Intent(Question2Activity.this, Question3Activity.class);
question3Intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
question3Intent.putExtra ("q1result", resultQ1);
question3Intent.putExtra ("q2result", resultQ2);
startActivity(question3Intent);
}
});
// Find the View that shows the next TextView
TextView previousQuestion = (TextView) findViewById(R.id.previous);
// Set a click listener on that View
previousQuestion.setOnClickListener(new View.OnClickListener() {
// The code in this method will be executed when next View is clicked on.
#Override
public void onClick(View view) {
Intent question1Intent = new Intent(Question2Activity.this, Question1Activity.class);
startActivity(question1Intent);
}
});
}
/**
* Check which checkbox was selected in the question 2
*
* #param checkBox1 is whether or not the user checked the checkbox1
* #param checkBox2 is whether or not the user checked the checkbox2
* #param checkBox3 is whether or not the user checked the checkbox3
* #return the score the user got for question 2
*/
private int calculateResultQ2(boolean checkBox1, boolean checkBox2, boolean checkBox3) {
int result = 0;
if (checkBox1 && checkBox2 && checkBox3) {
result = 1;
}
return result;
}
I would appreciate very much if anyone could help me out. Thank you!
EDIT: Below is my working code using sharedPreferences, the solution proposed by #tahsinRupam
package com.example.justynagolawska.quizappiteration2;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
public class Question2Activity extends AppCompatActivity {
SharedPreferences mypref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question2);
final CheckBox checkBox1Q2 = (CheckBox) findViewById(R.id.checkbox1Q2);
final CheckBox checkBox2Q2 = (CheckBox) findViewById(R.id.checkbox2Q2);
final CheckBox checkBox3Q2 = (CheckBox) findViewById(R.id.checkbox3Q2);
mypref = PreferenceManager.getDefaultSharedPreferences(this);
ActionBar actionbar = getSupportActionBar();
// Applies the custom action bar style
getSupportActionBar().setDisplayOptions(actionbar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.action_bar);
// Changes the action bar title
TextView title = (TextView) getSupportActionBar().getCustomView().findViewById(R.id.action_bar_title);
title.setText(R.string.q2_name);
//Getting the intent with score for question 1
Intent question2Intent = getIntent();
final int resultQ1 = question2Intent.getIntExtra("q1result", 0);
// Find the View that shows the next TextView
TextView nextQuestion = (TextView) findViewById(R.id.next);
// Set a click listener on that View
nextQuestion.setOnClickListener(new View.OnClickListener() {
// The code in this method will be executed when next View is clicked on.
#Override
public void onClick(View view) {
//Getting the answer to question 2 checkbox 1
boolean isCheckBox1Q2 = checkBox1Q2.isChecked();
//Getting the answer to question 2 checkbox 2
boolean isCheckBox2Q2 = checkBox2Q2.isChecked();
//Getting the answer to question 2 checkbox 3
boolean isCheckBox3Q2 = checkBox3Q2.isChecked();
//Calculate Question 2 score
int resultQ2 = calculateResultQ2(isCheckBox1Q2, isCheckBox2Q2, isCheckBox3Q2);
Intent question3Intent = new Intent(Question2Activity.this, Question3Activity.class);
question3Intent.putExtra ("q1result", resultQ1);
question3Intent.putExtra ("q2result", resultQ2);
startActivity(question3Intent);
}
});
// Find the View that shows the next TextView
TextView previousQuestion = (TextView) findViewById(R.id.previous);
// Set a click listener on that View
previousQuestion.setOnClickListener(new View.OnClickListener() {
// The code in this method will be executed when next View is clicked on.
#Override
public void onClick(View view) {
Intent question1Intent = new Intent(Question2Activity.this, Question1Activity.class);
startActivity(question1Intent);
}
});
}
/**
* Check which checkbox was selected in the question 2
*
* #param checkBox1 is whether or not the user checked the checkbox1
* #param checkBox2 is whether or not the user checked the checkbox2
* #param checkBox3 is whether or not the user checked the checkbox3
* #return the score the user got for question 2
*/
private int calculateResultQ2(boolean checkBox1, boolean checkBox2, boolean checkBox3) {
int result = 0;
if (checkBox1 && checkBox2 && checkBox3) {
result = 1;
}
return result;
}
#Override
protected void onPause() {
super.onPause();
//Getting the answer to question 2 checkbox 1
CheckBox checkBox1Q2 = (CheckBox) findViewById(R.id.checkbox1Q2);
boolean isCheckBox1Q2 = checkBox1Q2.isChecked();
//Getting the answer to question 2 checkbox 2
CheckBox checkBox2Q2 = (CheckBox) findViewById(R.id.checkbox2Q2);
boolean isCheckBox2Q2 = checkBox2Q2.isChecked();
//Getting the answer to question 2 checkbox 3
CheckBox checkBox3Q2 = (CheckBox) findViewById(R.id.checkbox3Q2);
boolean isCheckBox3Q2 = checkBox3Q2.isChecked();
if(isCheckBox1Q2 == true){
mypref.edit().putBoolean("Iscb1Checked", true).apply();
}
else if(isCheckBox1Q2 == false){
mypref.edit().putBoolean("Iscb1Checked", false).apply();
}
if(isCheckBox2Q2 == true){
mypref.edit().putBoolean("Iscb2Checked", true).apply();
}
else if(isCheckBox2Q2 == false){
mypref.edit().putBoolean("Iscb2Checked", false).apply();
}
if(isCheckBox3Q2 == true){
mypref.edit().putBoolean("Iscb3Checked", true).apply();
}
else if(isCheckBox3Q2 == false){
mypref.edit().putBoolean("Iscb3Checked", false).apply();
}
}
#Override
protected void onResume() {
super.onResume();
//Getting the answer to question 2 checkbox 1
CheckBox checkBox1Q2 = (CheckBox) findViewById(R.id.checkbox1Q2);
//Getting the answer to question 2 checkbox 2
CheckBox checkBox2Q2 = (CheckBox) findViewById(R.id.checkbox2Q2);
//Getting the answer to question 2 checkbox 3
CheckBox checkBox3Q2 = (CheckBox) findViewById(R.id.checkbox3Q2);
if(mypref.contains("Iscb1Checked")){
if(mypref.getBoolean("Iscb1Checked",false)){
checkBox1Q2.setChecked(true);
}
}
if(mypref.contains("Iscb2Checked")){
if(mypref.getBoolean("Iscb2Checked",false)){
checkBox2Q2.setChecked(true);
}
}
if(mypref.contains("Iscb3Checked")){
if(mypref.getBoolean("Iscb3Checked",false)){
checkBox3Q2.setChecked(true);
}
}
}
}
Please note that I replaced the below in the onPause(); method as I was getting null exception:
checkBox1Q2.isChecked()
!checkBox1Q2.isChecked()
with
isCheckBox1Q2 == true
isCheckBox1Q2 == false
You can use SharedPreference to store your value.
1) Declare checkbox and SharedPreference publicly:
CheckBox checkBox1Q2;
CheckBox checkBox2Q2;
CheckBox checkBox3Q2;
SharedPreferences mypref;
2) In your onCreate() initialize SharedPreference:
mypref = PreferenceManager.getDefaultSharedPreferences(this);
3) Save Checkbox states in onPause() (cause onPause() is called when the back button is pressed). You could declare in onStop() or onDestroy() too.
#Override
protected void onPause() {
super.onPause();
if(checkBox1Q2.isChecked()){
mypref.edit().putBoolean("Iscb1Checked", true).apply();
}
else if(!checkBox1Q2.isChecked()){
mypref.edit().putBoolean("Iscb1Checked", false).apply();
}
if(checkBox2Q2.isChecked()){
mypref.edit().putBoolean("Iscb2Checked", true).apply();
}
else if(!checkBox2Q2.isChecked()){
mypref.edit().putBoolean("Iscb2Checked", false).apply();
}
if(checkBox3Q2.isChecked()){
mypref.edit().putBoolean("Iscb3Checked", true).apply();
}
else if(!checkBox3Q2.isChecked()){
mypref.edit().putBoolean("Iscb3Checked", false).apply();
}
}
4) Get CheckBox states in onResume() method:
#Override
protected void onResume() {
super.onResume();
if(mypref.contains("Iscb1Checked")){
if(mypref.getBoolean("Iscb1Checked",false)){
checkBox1Q2.setChecked(true);
}
}
if(mypref.contains("Iscb2Checked")){
if(mypref.getBoolean("Iscb2Checked",false)){
checkBox2Q2.setChecked(true);
}
}
if(mypref.contains("Iscb3Checked")){
if(mypref.getBoolean("Iscb3Checked",false)){
checkBox3Q2.setChecked(true);
}
}
}
You're now getting the Checkbox view in onClick. Try to avoid that. Always get views (findViewById) in the initial part of onCreate (After setContentView).
I am trying to make an app where the user inputs a phone number into a EditText variable NumberBox which is than converted to int from string and used in the method intent.putExtra("address", PhoneNumberint); When I try to do this, the app just crashes, so please let me know what the problem is here. Is the conversion from string to int wrong in some way?
package com.example.module09;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
//variables
EditText NumberBox;
Button SMSButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//
NumberBox = (EditText) findViewById(R.id.NumberBox);
SMSButton = (Button) findViewById(R.id.SMSButton);
final int PhoneNumberint = Integer.parseInt(NumberBox.getText().toString());
//onclick
SMSButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.putExtra("address", PhoneNumberint);
intent.setType("vnd.android-dir/mms-sms");
startActivity(intent);
}
});
}
#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;
}
}
Just move this :
final int PhoneNumberint = Integer.parseInt(NumberBox.getText().toString());
from your onCreate method to the onClick method.
The app crashes because you have placed the above code in your onCreate method. Since at the time of Activity creation the value of EditText is null the String contains null. When null is parsed to Integer it throws an exception.
you try get value on onCreate method that is null, you must get value of that on button click like following code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//
NumberBox = (EditText) findViewById(R.id.NumberBox);
SMSButton = (Button) findViewById(R.id.SMSButton);
//onclick
SMSButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
PhoneNumberint = Integer.parseInt(NumberBox.getText().toString());
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.putExtra("address", PhoneNumberint);
intent.setType("vnd.android-dir/mms-sms");
startActivity(intent);
}
});
You can't perform this on onCreate() method
final int PhoneNumberint = Integer.parseInt(NumberBox.getText().toString());
At first time your String contains null data because it always be null values for your EditText and that's why you will be always get null pointer because you can't parse null value to int.
So better way it to move that line on Click event of Button.
The app crashes because of NumberFormatException
The problem lies where you are extracting text from EditText before it is being set. If the content of EditText is empty/null string, Integer.parseInt will throw java.lang.NumberFormatException
The culprit is this line:
final int PhoneNumberint = Integer.parseInt(NumberBox.getText().toString());
To fix this, move this line under onClick(). But the App will still crash, if the button is clicked without inputting anything in EditText.
Before parsing the String to Int, write to check if the String is empty/null.
On the lighter side, there is no need of final keyword here.
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 fairly new to programming and I am learning to develop in Java and building Android applications.
I am trying to create a Dreidel game, on my xml file, I have a button, an imageview, and a TextView (I will be working on keeping the score a little later, I can figure that out on my own easily enough I imagine).
But the objective is that when I push the button, a random number generator produces a number from 0-3,
If 0, I want the TextBox to display "You get nothing"
If 1, I want the TextBox to display something else
If 2, I want the TextBox to display something else
If 3, I want the TextBox to display something else
Here is the code. When I run it in the Android Emulator, it starts up but nothing happens when I click the button
package com.secondtry;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
Button spinButton;
TextView display;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
display = (TextView) findViewById(R.id.widget34);
spinButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Random numGen = new Random();
numGen.nextInt(4);
if (numGen.nextInt() == 0)
{
display.setText("You get nothing");
}
else if (numGen.nextInt() == 1)
{
display.setText("You get half!");
}
else if (numGen.nextInt() == 2)
{
display.setText("You get it all");
}
else if (numGen.nextInt() == 3)
{
display.setText("Chip in a coin");
} }
});
}
}
Use numGen.nextInt(4) instead of numGen.nextInt() in your condition. Grab its value inside a variable(say x) and use that value in every condition.
You may try this:
int ran = numGen.nextInt(4);
switch (ran){
case 0:
display.setText("You get nothing");
break;
case 1:
display.setText("You get half!");
break;
case 2:
display.setText("You get it all");
break;
case 3:
display.setText("Chip in a coin");
break;
}
You need to either define your button in onCreate with something like
final Button spinButton = (Button) findViewById(R.id.spinbuttonIdInXML);
Or pull the onClick outside of the onCreate:
#Override
public void onCreate(Bundle savedInstanceState) {
...
}
#Override
public void onClick(View v) {
...
}
Define your Button in OnCreate Like this..
spinButton = (Button)findViewById(R.id.urbuttonid);
updated try this
public class MainActivity extends Activity {
/** Called when the activity is first created. */
Button spinButton;
TextView display;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
spinButton = (Button)findViewById(R.id.ButtonId);
display = (TextView) findViewById(R.id.widget34);
spinButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Random numGen = new Random();
int rNumber = numGen.nextInt(4);
if (rNumber == 0)
{
display.setText("You get nothing");
}
else if (rNumber == 1)
{
display.setText("You get half!");
}
else if (rNumber == 2)
{
display.setText("You get it all");
}
else if (rNumber == 3)
{
display.setText("Chip in a coin");
} }
});
}
}
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(){}