I'm supposed to generate two random numbers, then find the perimeter of a rectangle with them. Then it allows the User to input their answer in a EditText, when the User inputs their answer in the EditText, There is a submit button so that when the user clicks it, it lets the person know if their answer is correct or incorrect. This is displayed as a toast message. The problem i have, is when i click the submit button, it always show says "The answer is incorrect even if i put in the right value in the EditText. Would appreciate some help. Thank You
public class Perimeter extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_perimeter);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
public void PerimeterGame(View view) {
Random rand = new Random();
int number = rand.nextInt(12) + 1;
TextView myText = (TextView) findViewById(R.id.rand1);
String myString = String.valueOf(number);
myText.setText(myString);
Random rand2 = new Random();
int number2 = rand2.nextInt(12) + 1;
TextView myText2 = (TextView) findViewById(R.id.rand2);
String myString2 = String.valueOf(number2);
myText2.setText(myString2);
((TextView) findViewById(R.id.question)).setText
("Find the perimeter of a rectange with a width of " + myString + "cm" + " and " + "length of " + myString2 + "cm" + ".");
}
public void AnswerCheck(View view){
int perimeter;
Random randOne = new Random();
int number = randOne.nextInt(12) + 1;
TextView myText = (TextView) findViewById(R.id.rand1);
String myString = String.valueOf(number);
myText.setText(myString);
Random randTwo = new Random();
int number2 = randTwo.nextInt(12) + 1;
TextView myText2 = (TextView) findViewById(R.id.rand2);
String myString2 = String.valueOf(number2);
myText2.setText(myString2);
EditText num = (EditText)findViewById(R.id.answertext);
int val = Integer.parseInt(num.getText().toString() );
perimeter=(number+number2+number+number2);
if(val==perimeter){
Toast.makeText(this, "The answer is correct", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(this, "The answer is incorrect ", Toast.LENGTH_SHORT).show();
}
}
}
Your problem is that you are generating completely different random numbers when you go to check the answer. You need to save the numbers in instance variables like so.
public class Perimeter extends AppCompatActivity {
private int number1, number2;
private Random rand;
onCreate() {
rand = new Random();
}
PerimeterGame(View view) {
number1 = rand.nextInt(12) + 1;
number2 = rand.nextInt(12) + 1;
}
AnswerCheck(View view) {
// Don't make new random variables here, just check your inputs.
EditText num = (EditText)findViewById(R.id.answertext);
int val = Integer.parseInt(num.getText().toString() );
int perimeter= 2*(number + number2);
if (val == perimeter) { }
}
}
In AnswerCheck you dont need to generate new numbers again.. you need to get old generated numbers in first method PerimeterGame() and do your formula with them.
Related
I made a code where user put value between some range and my code generate random number for them. Randomization working properly but when fields are blank my app is crash how should I fix it.
randNum.java
Button generateNum = findViewById(R.id.generate_number);
generateNum.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText et = findViewById(R.id.fromNum);
String sTextFromET = et.getText().toString();
int fNum = Integer.valueOf(sTextFromET);
EditText et1 = findViewById(R.id.toNum);
String sTextFromET1 = et1.getText().toString();
int sNum = Integer.valueOf(sTextFromET1);
TextView ans = findViewById(R.id.ans);
// if(sNum == null || fNum == null){
//
// ans.setText(getString(R.string.enterNumError));
//
// }
// else
if(sNum < fNum){
ans.setText(getString(R.string.max_min_error));
}else {
final int random = new Random().nextInt((sNum - fNum) + 1) + fNum;
String ras = Integer.toString(random);
ans.setText(ras);
}
}
});
I try to use null but it is not working.
You need to put validation first on button click. (For checking if user has entered nothing or just spaces in any of edittexts).
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
strNum1 = edtl.getText().toString().trim();
strNum2 = edt2.getText().toString().trim();
if (strNum1.length() == 0)
{
showAlert("Please enter Num 1");
}
else if (strNum2.length() == 0)
{
showAlert("Please enter Num 2");
}
else
{
int numvalue1 = Integer.parseInt(strNum1);
int numvalue2 = Integer.parseInt(strNum2);
generateNum (numvalue1, numvalue2); //Call your function for generation of random number here
//do your stuff here
}
}
});
Hope this helps you understand the validation of forms for empty input fields.
P.S: I would recommend you put inputType attribute for your EditTexts if you have not added it already in xml file like:
android:inputType="number"
So you can avoid exception at Integer.parseInt if user enters any alphabet or symbol.
You need to handle NumberFormatException thrown by Integer.valueOf() function
try {
EditText et = findViewById(R.id.fromNum);
String sTextFromET = et.getText().toString();
int fNum = Integer.valueOf(sTextFromET);
EditText et1 = findViewById(R.id.toNum);
String sTextFromET1 = et1.getText().toString();
int sNum = Integer.valueOf(sTextFromET1);
TextView ans = findViewById(R.id.ans);
if(sNum < fNum){
ans.setText(getString(R.string.max_min_error));
}else {
final int random = new Random().nextInt((sNum - fNum) + 1) + fNum;
String ras = Integer.toString(random);
ans.setText(ras);
}
}catch(NumberFormatException e){
Toast.makeText(this, "Invalid Input", Toast.LENGTH_SHORT).show();
}
I am trying to build a Bengali calculator. Here is the layout of English calculator :
By editing layout I can easily replace English digits with Bengali digits. But when it comes to the calculation i am unable to do it. Like i want it to calculate in Bengali too. e.g it will perform in Bengali like this (২+২=৪) instead of (2+2=4). I have tried the replacing method but it didn't work.
Bengali digits(০ ১ ২ ৩ ৪ ৫ ৬ ৭ ৮ ৯)
English digits(1 2 3 4 5 6 7 8 9)
Thank you for your time.
public class MainActivity extends AppCompatActivity {
private TextView screen;
private String str2, result, str, sign;
private double a, b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
screen = (TextView) findViewById(R.id.textview);
str = "";
}
public void onclick(View v) {
Button button = (Button) v;
str += button.getText().toString();
screen.setText(str);
a = Double.parseDouble(str);
}
public void onclicksign(View v) {
Button button = (Button) v;
sign = button.getText().toString();
screen.setText(sign);
str = "";
}
public void calculate(View v) {
Button button = (Button) v;
str2 = screen.getText().toString();
b = Double.parseDouble(str2);
if (sign.equals("+")) {
result = a + b + "";
} else if (sign.equals("-")) {
result = a - b + "";
} else if (sign.equals("*")) {
result = a * b + "";
} else if (sign.equals("/")) {
result = a / b + "";
} else {
screen.setText("?????? ???");
}
{
screen.setText(result);
}
}
}
Your code tries to extract numerical values from the text on buttons.
You should write custom Double parser which parses Bengali number text to numerical value.
Also you should write a method which converts numerical double value to Bengali number text. You have to use this method while setting screen text.
public class MainActivity extends AppCompatActivity {
private TextView screen;
private String str2, result, str, sign;
private double a, b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
screen = (TextView) findViewById(R.id.textview);
str = "";
}
public void onclick(View v) {
Button button = (Button) v;
str += button.getText().toString();
screen.setText(str);
a = BengaliUtils.toDouble(str);
}
public void onclicksign(View v) {
Button button = (Button) v;
sign = button.getText().toString();
screen.setText(sign);
str = "";
}
public void calculate(View v) {
Button button = (Button) v;
str2 = screen.getText().toString();
b = BengaliUtils.toDouble(str2);
if (sign.equals("+")) {
result = a + b + "";
} else if (sign.equals("-")) {
result = a - b + "";
} else if (sign.equals("*")) {
result = a * b + "";
} else if (sign.equals("/")) {
result = a / b + "";
} else {
screen.setText("?????? ???");
}
{
screen.setText(BengaliUtils.toString(result));
}
}
}
class BengaliUtils {
static String toString(double value) {
//TODO implement logic
// You can convert value to regular number text, and then replace each char with the Bengali version. The performance could be improved with better logic.
return text;
}
static double toDouble(String text) {
//TODO implement logic
//You can do that, first replace each Bengali char with normal number char. The use Double.parse on new text. The performance could be improved with better logic.
return value;
}
}
#Override
public void onClick(View view) {
String num = editText.getText().toString();
//split the num
char[] charArray = num.toCharArray();
StringBuilder stringBuilder = new StringBuilder(charArray.length);
// loop and convert using switch case
for (int i=0; i<charArray.length; i++ ){
char character = charArray[i];
switch (character){
case '.':
stringBuilder.append(".");
break;
case '0':
stringBuilder.append("০");
break;
case '1':
stringBuilder.append("১");
break;
}
}
//Final result..
textView.setText(stringBuilder);
}
Try above code...
Here is the output
NOTE
I am taking English numbers from EditText on Button click. You will
have to change that in your code.
Currently, switch can handle 0,1,.(decimal) only. You can easily
add cases for other numbers too.
Please Check this answer too. Convert String to another locale in java
This is my Code. When the user enters their answer and press the Submit Button which is the AnswerCheck Method, i would like the score to be shown in a TextView for example - if they input the right answer, the TextView would state 1 correct out of 1. I would like some help, Thanks
public class Perimeter extends AppCompatActivity {
private int number;
private int number2;
private String myString;
private String myString2;
private int perimeter;
private Random rand;
private Random rand2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_perimeter);
rand = new Random();
rand2 = new Random();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
public void PerimeterGame(View view) {
number = rand.nextInt(12) + 1;
TextView myText = (TextView) findViewById(R.id.rand1);
myString = String.valueOf(number);
myText.setText(myString);
number2 = rand2.nextInt(12) + 1;
TextView myText2 = (TextView) findViewById(R.id.rand2);
myString2 = String.valueOf(number2);
myText2.setText(myString2);
((TextView) findViewById(R.id.question)).setText
("Find the perimeter of a rectange with a width of " + myString + "cm" + " and " + "length of " + myString2 + "cm" + ".");
}
public void AnswerCheck(View view) {
EditText num = (EditText) findViewById(R.id.answertext);
int val = Integer.parseInt(num.getText().toString());
perimeter = (number + number2 + number + number2);
if (val == perimeter) {
Toast.makeText(this, "The answer is correct", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "The answer is incorrect ", Toast.LENGTH_SHORT).show();
}
findViewById(R.id.showsolbutton).setEnabled(true);
}
}
Set two global int variables
private int totalQuestion = 0;
and private int correctQuestions = 0;
Inside public void PerimeterGame(View view) increment totalQuestion by one.
When the answer is correct, inside public void AnswerCheck(View view) increment correctQuestion by one.
Finally, display the text
youTextView.setText(String.valueOf(correctQuestions) + " correct out of " + String.valueOf(totalQuestion));
Hope it helps.
public class Perimeter extends AppCompatActivity {
// Code ommitted
private int totalQuestion = 0 ;
private int correctQuestions = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
// Code ommitted
}
public void PerimeterGame(View view) {
// Increment totalQuestion
totalQuestion++;
number = rand.nextInt(12) + 1;
TextView myText = (TextView) findViewById(R.id.rand1);
myString = String.valueOf(number);
myText.setText(myString);
number2 = rand2.nextInt(12) + 1;
TextView myText2 = (TextView) findViewById(R.id.rand2);
myString2 = String.valueOf(number2);
myText2.setText(myString2);
((TextView) findViewById(R.id.question)).setText
("Find the perimeter of a rectange with a width of " + myString + "cm" + " and " + "length of " + myString2 + "cm" + ".");
}
public void AnswerCheck(View view) {
EditText num = (EditText) findViewById(R.id.answertext);
int val = Integer.parseInt(num.getText().toString());
perimeter = (number + number2 + number + number2);
if (val == perimeter) {
correctQuestions++;
Toast.makeText(this, "The answer is correct", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "The answer is incorrect ", Toast.LENGTH_SHORT).show();
}
findViewById(R.id.showsolbutton).setEnabled(true);
// Display text
youTextView.setText(String.valueOf(correctQuestions) + " correct out of " + String.valueOf(totalQuestion));
}
}
In my Android app I am calculating a double value using values entered into EditTexts and trying to put the answer into a TextView. My code is this:
double scoreDouble;
TextView score;
EditText gpa;
EditText sat;
EditText act;
Button calc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gpa = (EditText) findViewById(R.id.gpa);
String gpaString = gpa.getText().toString();
if(gpaString.equals("")){
gpaString = "0";
}
final double gpaDouble = Double.parseDouble(gpaString);
sat = (EditText) findViewById(R.id.sat);
String satString = sat.getText().toString();
if(satString.equals("")){
satString = "0";
}
final int satInt = Integer.parseInt(satString);
act = (EditText) findViewById(R.id.act);
String actString = act.getText().toString();
if(actString.equals("")){
actString = "0";
}
final int actInt = Integer.parseInt(actString);
score = (TextView) findViewById(R.id.score);
calc = (Button) findViewById(R.id.calc);
calc.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(actInt/36>satInt/2400){
scoreDouble= (0.6*gpaDouble*25)+(0.4*(actInt/36)*100);
String scoreString = Double.toString(scoreDouble);
score.setText("Your score is "+scoreString);
}else{
scoreDouble = (0.6*gpaDouble*25)+(0.4*(satInt/2400)*100);
String scoreString = Double.toString(scoreDouble);
score.setText("Your score is "+scoreString);
}
}
});
}
As of now, when the button is pressed the TextView says: "Your score is 0.0." I feel this has something to do with the fact that I set the default values of the EditTexts to 0. Before I did this, I was getting an error stating NumberFormatException: invalid double: "". If this is the problem, how should I fix it. If that is not the problem, what it?
You define the actInt and satInt as final variables, and they will be assigned to a value only once (when the execution of the onCreate method) and the initial value will be zero as at the begining the edittext contain nothing.
To solve this issue:
move he actInt and satInt from local variables to a field variables and remove the final keyword. (I mean define those variables as a private variables inside the class) and assign the values for the variables inside the onclick Method.
public class test extends Activity {
double scoreDouble;
TextView score;
EditText gpa;
EditText sat;
EditText act;
Button calc;
private int satInt;
private int actInt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gpa = (EditText) findViewById(R.id.gpa);
sat = (EditText) findViewById(R.id.sat);
act = (EditText) findViewById(R.id.act);
score = (TextView) findViewById(R.id.score);
calc = (Button) findViewById(R.id.calc);
calc.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String gpaString = gpa.getText().toString();
if (gpaString.equals("")) {
gpaString = "0";
}
double gpaDouble = Double.parseDouble(gpaString);
String satString = sat.getText().toString();
if (satString.equals("")) {
satString = "0";
}
int satInt = Integer.parseInt(satString);
String actString = act.getText().toString();
if (actString.equals("")) {
actString = "0";
}
int actInt = Integer.parseInt(actString);
if (actInt / 36 > satInt / 2400) {
scoreDouble = (0.6 * gpaDouble * 25)
+ (0.4 * (actInt / 36) * 100);
String scoreString = Double.toString(scoreDouble);
score.setText("Your score is " + scoreString);
} else {
scoreDouble = (0.6 * gpaDouble * 25)
+ (0.4 * (satInt / 2400) * 100);
String scoreString = Double.toString(scoreDouble);
score.setText("Your score is " + scoreString);
}
}
});
}
}
You are doing everything on your onCreate method. So all your code is called at the start of your application. At this moment, your EditTexts are empty and your code goes to these parts:
if(gpaString.equals("")){
gpaString = "0";
}
if(actString.equals("")){
actString = "0";
}
if (actString.equals("")) {
actString = "0";
}
Which means that your values gpaDouble, actInt and satInt are equals 0.
Then, you are doing the following:
scoreDouble = (0.6*gpaDouble*25)+(0.4*(satInt/36)*100);
and this:
scoreDouble = (0.6*gpaDouble*25)+(0.4*(satInt/2400)*100);
With the 0 values, your scoreDouble value can only be equal to 0.
To fix it, get your EditTexts' texts in the onClick method of your Button.
I have a function to find an employee's id number from my sqlite database. The function allows the user to look up by id or name (first and/or last); therefore it creates several dialog boxes and finds the data through an If Else Then tree. Here's the code for those who like that sort of thing:
public String getEmployeeID() {
final CharSequence[] items = {"By ID", "By Name", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(LibraryScreen.this);
builder.setTitle("Find Employee");
builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if(items[item].equals("Cancel")) {
dialog.cancel();
empid = "";
} else if(items[item].equals("By ID")) {
dialog.cancel();
final Dialog dialog2 = new Dialog(LibraryScreen.this);
dialog2.setContentView(R.layout.peopledialog);
dialog2.setTitle("Employee ID");
dialog2.setCancelable(true);
//Set Visibility of the Rows
TableRow tblrow1 = (TableRow) dialog2.findViewById(R.id.trGeneral);
tblrow1.setVisibility(0);
//Set Captions for Rows
TextView txtvw1 = (TextView) dialog2.findViewById(R.id.tvGeneral);
txtvw1.setText("Employee ID");
//Set Up Edit Text Boxes
EditText edttxt1 = (EditText) dialog2.findViewById(R.id.txtGeneral);
//Set Input Type
edttxt1.setRawInputType(0x00000002);//numbers
edttxt1.setText("");
//set max lines
edttxt1.setMaxLines(1);
//Set MaxLength
int maxLength;
maxLength = 15;
InputFilter[] FilterArray = new InputFilter[1];
FilterArray[0] = new InputFilter.LengthFilter(maxLength);
edttxt1.setFilters(FilterArray);
Button button = (Button) dialog2.findViewById(R.id.btnTxtDiaSav);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
EditText emplid = (EditText) dialog2.findViewById(R.id.txtGeneral);
String newemp = "";
db.open();
Cursor c = db.getEmployee(emplid.getText().toString());
if(c.moveToFirst()) {
empid = c.getString(c.getColumnIndex("employeeid"));
} else {
Toast.makeText(LibraryScreen.this, "No ID Match", Toast.LENGTH_LONG).show();
empid = "";
}
c.close();
db.close();
dialog2.dismiss();
}
});
Button buttonCan = (Button) dialog2.findViewById(R.id.btnTxtDiaCan);
buttonCan.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog2.dismiss();
empid = "";
}
});
dialog2.show();
} else if(items[item].equals("By Name")) {
dialog.cancel();
final Dialog dialog1 = new Dialog(LibraryScreen.this);
dialog1.setContentView(R.layout.peopledialog);
dialog1.setTitle("Employee's Name");
dialog1.setCancelable(true);
//Set Visibility of the Rows
TableRow tblrow1 = (TableRow) dialog1.findViewById(R.id.trGeneral);
tblrow1.setVisibility(0);
//Set Captions for Rows
TextView txtvw1 = (TextView) dialog1.findViewById(R.id.tvGeneral);
txtvw1.setText("Employee Name");
//Set Up Edit Text Boxes
EditText edttxt1 = (EditText) dialog1.findViewById(R.id.txtGeneral);
//Set Input Type
edttxt1.setRawInputType(0x00002001);//cap words
edttxt1.setText("");
//set max lines
edttxt1.setMaxLines(1);
//Set MaxLength
int maxLength;
maxLength = 50;
InputFilter[] FilterArray = new InputFilter[1];
FilterArray[0] = new InputFilter.LengthFilter(maxLength);
edttxt1.setFilters(FilterArray);
Button button = (Button) dialog1.findViewById(R.id.btnTxtDiaSav);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
EditText emplid = (EditText) dialog1.findViewById(R.id.txtGeneral);
String firstname = emplid.getText().toString();
String lastname = "";
String matchlist = "";
String temptext = "";
int matchcount = 0;
if(firstname.lastIndexOf(" ") <= 0) {
lastname = firstname;
firstname = "X";
} else {
lastname = firstname.substring(firstname.lastIndexOf(" ") + 1);
firstname = firstname.substring(0, firstname.lastIndexOf(" "));
}
db.open();
Cursor c1, c2;
String titletext = "";
if(firstname.length() > 0) {
c1 = db.getEmployeeByName(lastname, firstname);
if(c1.getCount() == 0) {
c1 = db.getRowByFieldTextOrdered("employees", "lastname", lastname, "lastname, firstname");
if(c1.getCount() == 0) {
Toast.makeText(LibraryScreen.this, "No matching Employees.", Toast.LENGTH_LONG).show();
empid = "";
}
}
if(c1.getCount() > 0) {
do {
c2 = db.getRowByField("orgcodes", "manager", c1.getString(c1.getColumnIndex("employeeid")));
if(c2.moveToFirst()) {
if(c2.getString(c2.getColumnIndex("orgcode")).substring(9, 10).equals("0")) {
if(c2.getString(c2.getColumnIndex("orgcode")).substring(7, 8).equals("0")) {
if(c2.getString(c2.getColumnIndex("orgcode")).substring(5, 6).equals("0")) {
if(c2.getString(c2.getColumnIndex("orgcode")).substring(4, 5).equals("0")) {
if(c2.getString(c2.getColumnIndex("orgcode")).substring(3, 4).equals("0")) {
titletext = "Top Brass";
} else {
titletext = "Senior VP";
}
} else {
titletext = "VP";
}
} else {
titletext = "Director";
}
} else {
titletext = "Senior Manager";
}
} else {
titletext = "Manager";
}
} else {
titletext = "Employee";
}
matchcount++;
matchlist = matchlist + c1.getString(c1.getColumnIndex("employeeid")) + ": " + c1.getString(c1.getColumnIndex("firstname")) + " " + c1.getString(c1.getColumnIndex("lastname")) + ": " + titletext + "|";
} while(c1.moveToNext());
}
} else {
empid = "";
}
if(matchcount == 0) {
db.close();
Toast.makeText(LibraryScreen.this, "No matching Employees.", Toast.LENGTH_LONG).show();
empid = "";
} else {
final CharSequence[] items = new CharSequence[matchcount + 1];
items[0] = "(Cancel)";
for(int i = 1; i <= matchcount; i++) {
items[i] = matchlist.substring(0, matchlist.indexOf("|"));
matchlist = matchlist.substring(matchlist.indexOf("|") + 1);
}
db.close();
AlertDialog.Builder builder1 = new AlertDialog.Builder(LibraryScreen.this);
builder1.setTitle("Select Employee");
builder1.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if(items[item].equals("(Cancel)")) {
dialog.cancel();
empid = "";
} else {
String wasted = items[item].toString();
empid = wasted.substring(0, wasted.indexOf(":"));
dialog.cancel();
}
}
});
AlertDialog alert1 = builder1.create();
alert1.show();
}
dialog1.dismiss();
}
});
Button buttonCan = (Button) dialog1.findViewById(R.id.btnTxtDiaCan);
buttonCan.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog1.dismiss();
empid = "";
}
});
dialog1.show();
}
}
});
AlertDialog alert = builder.create();
alert.show();
return empid;
}
I use the employee id for a variety of functions through multiple activities in my program. Up to now, I've simply pasted the code under each listener that needs the id, but that is such a waste of space IMHO.
My question:
Is there a way to put this function somewhere that can be called from many different activities?
If so:
How do I do that?
How do I set the context for the dialog boxes for multiple activities?
How do I get the employee id back to the function that needs it?
I'm sure this has been asked before, but I haven't been able to find it online: actually, I'm not even sure how to word the query right. My attempts have come up woefully short.
A little late to the party - but recorded for posterity:
Read up on the Application class:
Base class for those who need to maintain global application state.
You can provide your own implementation by specifying its name in your
AndroidManifest.xml's tag, which will cause that class
to be instantiated for you when the process for your
application/package is created.
Basically, this would give you the ability to obtain a single object that represents your running application (think of it as a singleton that returns an instance of your running app).
You first start off by creating a class that extends Application base class and defining any common code that is used throughout your application
import android.app.Application;
public class MyApplication extends Application {
public void myGlobalBusinessLogic() {
//
}
}
Then tell your application to use the MyApplication class instead of the default Application class via the <application> node in your app manifest:
<application android:icon="#drawable/icon" android:label="#string/app_name"
android:name="MyApplication">
Finally, when you need to get to your common function just do something like:
MyApplication application = (MyApplication) getApplication();
application.myGlobalBusinessLogic();
If you need to get the context from any part of your application, you can simple return it by calling getApplicationContext() (defined in the base Application class) via a getter method within your custom application class.