What I want is that by default C is 0 but when the user adds 2 then it should display 2 and then when the user adds 4 it should be 6 but instead it displays 4
Any help would be appreciated!
public void addCash(View view) {
//Intent intent = new Intent(this, Main.class);
EditText val1 = (EditText) findViewById(R.id.num);
int b = 0;
int a = 0;
int c = 0;
int d = 0;
a = Integer.parseInt(val1.getText().toString());
if (c == 0) {
c = a + b;
}
else {
c = c + a;
}
TextView result = (TextView) findViewById(R.id.outPut);
result.setText(""+c);
//startActivity(intent);
}
variable c is local to this function and every time function is called it initialize c = 0 .
So every time only if condition will run.
else condition will never executed.
you can declare c as global ....
Initialize your variable c with the value of the textview like this:
TextView result = (TextView) findViewById(R.id.outPut);
int c = Integer.parseInt(val1.getText().toString());
Edit: if the TextView by default is not set to 0 then you should consider doing an additional check.
Initialize "c" as a global member variable of your activity.Because instance of this will remain throughout the activity whereas if you initialize it as local vairable every time when you call method new variable instance is created
This as the global instance inside your activity
private int c = 0;
These "a",b","d" be initialzed again and again when call addcash method
public void addCash(View view) {
//Intent intent = new Intent(this, Main.class);
EditText val1 = (EditText) findViewById(R.id.num);
int b = 0;
int a = 0;
int d = 0;
a = Integer.parseInt(val1.getText().toString());
if (c == 0) {
c = a + b;
}
else {
c = c + a;
}
TextView result = (TextView) findViewById(R.id.outPut);
result.setText(""+c);
Also replace below line of code with c = c + a as "b" will be always zero according to your code
if (c == 0)
{
c = a + b;
}
For more information check this link
http://www.cafeaulait.org/course/week3/11.html
As the other answers already stated, you are using local variables, which are initialized at each method call.
class SomeActivity {
private int c = 3; // Instance variable being initialized to 3. When you
// leave out the "= 3" part, then it is initialized
// to 0.
public void addCash(View v) {
// Now if you add something to c, it will persist between multiple
// method calls
EditText inputField = (EditText) findViewById(R.id.num);
EditText outputField = (TextView) findViewById(R.id.outPut);
c += Integer.parseInt(inputField.getText().toString());
outputField.setText(String.valueOf(c));
}
}
Related
The error I'm getting :
Process: com.example.numerology, PID: 4012
java.lang.ArrayIndexOutOfBoundsException: length=14; index=14
at com.example.numerology.MainActivity$3.onClick(MainActivity.java:90)
at android.view.View.performClick(View.java:6608)
at android.view.View.performClickInternal(View.java:6585)
at android.view.View.access$3100(View.java:785)
at android.view.View$PerformClick.run(View.java:25921)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6810)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
My code:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText e1 = findViewById(R.id.name);
final EditText e2 = findViewById(R.id.date);
final EditText e3 = findViewById(R.id.month);
final EditText e4 = findViewById(R.id.year);
Button b = findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
char[] n = e1.getText().toString().toCharArray();
int date = Integer.parseInt(e2.getText().toString());
int month = Integer.parseInt(e3.getText().toString());
int year = Integer.parseInt(e4.getText().toString());
int nn = 0;
int driver = date, conductor = date + month + year;
int temp, k = 0;
Intent i1 = new Intent(MainActivity.this, Main2Activity.class);
i1.putExtra("NN", nn);
i1.putExtra("Driver", driver);
i1.putExtra("Conductor", conductor);
startActivity(i1);
}
});
This is the major part of the code I'm using, I think the problem is related to the character array.
This is how I'm using the char array:
if (n[i] == 'f' || n[i] == 'F' || n[i] == 'p' || n[i] == 'P') {
nn += 8;
}
So this activity does pop up on the screen but when I press the button to jump to the next activity the app crashes leaving the error I specified above.
Gonna need some help fixing this, Thank you.
Array indexes start from 0 and end at length-1. Your code below is accessing it wrong as you are using <= with length, thus your last access for i will be length and not length-1. So change your loop
for (i = 1; i <= e1.getText().toString().length(); i++)
to
int len = e1.getText().toString().length();
for (i = 0; i < len ; i++)
I've got a [DONE] button that's supposed to check 2 entries's results. One of them is an [EditText--inputType:number] and the other is a [TextView] that increments when a certain button is pressed.
What I'm trying to do is check whether the EditText has an integer or is null, and check the contents of the TextView. if they both are greater than Zero. I add them up and send the total to my main activity. Here's the code i have so far.
public void returnbtn(View view) {
// Initialize insert textView
EditText insertcountBtn = findViewById(R.id.insertPushup);
// Initialize counter textView
TextView givencountBtn = findViewById(R.id.showCount);
// get added int stuff from the insert textField
int insertcountInt =
Integer.parseInt(insertcountBtn.getText().toString());
// get string stuff from counter textView
String givencountString = givencountBtn.getText().toString();
// convert counter textView to int.
Integer givencountInt = Integer.parseInt(givencountString);
if (givencountInt <= 0 && insertcountInt <= 0){
Total = 0;
} else if (givencountInt > 0 && insertcountInt <= 0) {
Total = givencountInt;
} else if (givencountInt <= 0 && insertcountInt > 0) {
Total = insertcountInt;
} else if (givencountInt > 0 && insertcountInt > 0){
// Add Counter textView and Insert textView to an Int Total
Total = givencountInt + insertcountInt;
}
// Create an Intent to return to the mainActivity.
Intent beginPushup = new Intent(this, MainActivity.class);
// Pass the current number to the push-up Counter activity.
beginPushup.putExtra(TOTAL_DONE, Total);
// Start mainActivity.
startActivity(beginPushup);
}
The problem i'm having is with either textView or EditText i'm not sure. All i know is that if i fill them both and click done it adds them up and transfers the total to mainActivity as expected. If I add values to EditText and leave TextView with 0 it also does what it's meant to do. But if I increment TextView and leave EditText blank, it does not transfer my TextView integer and crashes app.
Could i be detecting the editText wrong, because i think that's the reason.
If so what's the right way?
----- First && Second Answer Edits -----
int insertcountInt;
String insertcountString =
String.valueOf(insertcountBtn.getText());
try {
insertcountInt =
Integer.parseInt(insertcountBtn.getText().toString());
if (insertcountInt <= 0 || insertcountString == " ") Total =
givencountInt;
if (insertcountInt > 0 ) Total = givencountInt +
insertcountInt;
} catch (NumberFormatException e) {
insertcountInt = 0;
}
Good news is no more crash, but unless I fill the EditText with something, I'm not receiving my Integer in mainActivity. This is getting interesting. * I think it's a play of the if statements which I've restructures, but no luck so far. *
----- Updated Working Code For Any Future Requests -----
public void filledChecker() {
// Initialize insert textView
EditText insertcountBtn =
findViewById(R.id.insertPushup);
// Initialize counter textView
TextView givencountBtn = findViewById(R.id.showCount);
int insertcountInt = 0;
int givencountInt = 0;
// get added int stuff from the insert textField
if (!TextUtils.isEmpty(insertcountBtn.getText()) &&
TextUtils.isDigitsOnly(insertcountBtn.getText())) {
insertcountInt =
Integer.parseInt(insertcountBtn.getText().toString());
}
// get string stuff from counter textView
String givencountString = givencountBtn.getText().toString();
if (!TextUtils.isEmpty(givencountString) &&
TextUtils.isDigitsOnly(givencountString)) {
givencountInt = Integer.parseInt(givencountString);
}
if (insertcountInt <= 0) {
Total = givencountInt;
}
if (insertcountInt > 0) {
Total = givencountInt + insertcountInt;
}
}
public void returnbtn(View view) {
// Create an Intent to return to the mainActivity.
Intent beginPushup = new Intent(this, MainActivity.class);
filledChecker();
Integer current_Id = getIntent().getIntExtra(GIVEN_ID, 0);
// Pass the current number to the push-up Counter activity.
if (current_Id == 1) beginPushup.putExtra(TOTAL_P_DONE,
Total);
if (current_Id == 2) beginPushup.putExtra(TOTAL_S_DONE,
Total);
if (current_Id == 3) beginPushup.putExtra(TOTAL_C_DONE,
Total);
if (current_Id == 4) beginPushup.putExtra(TOTAL_SQ_DONE,
Total);
beginPushup.putExtra(GIVEN_ID, current_Id);
// Start mainActivity.
startActivity(beginPushup);
}
I As you can see I ended up dividing the if-logic from the Intent to Transfer to main Activity. This way they're both simple. And using the Do Not Repeat Yourself i did the same thing to the rest of my other buttons as you can see with all the if's in [returnbtn] method. I also simplified the if statement aside from the ones i was helped with. I ended up needing 2 if statements to manage getting a total from the 2 entries. Thanks again for the help everyone. Ohh the try-except didn't seem necessary so i deprecated them. as the app gets more complex i'll add them if necessary.
As the other answer explained, the issue with your code is that when the EditText is blank then parsing "null" is causing exception. So you just have to insure that if content is null then just use 0(Zero) value. You can try this:
public void returnbtn(View view) {
// Initialize insert textView
EditText insertcountBtn = findViewById(R.id.insertPushup);
// Initialize counter textView
TextView givencountBtn = findViewById(R.id.showCount);
int insertcountInt = 0;
int givencountInt = 0;
// get added int stuff from the insert textField
if (!TextUtils.isEmpty(insertcountBtn.getText()) && TextUtils.isDigitsOnly(insertcountBtn.getText())) {
insertcountInt = Integer.parseInt(insertcountBtn.getText().toString());
}
// get string stuff from counter textView
String givencountString = givencountBtn.getText().toString();
if (!TextUtils.isEmpty(givencountString) && TextUtils.isDigitsOnly(givencountString)) {
givencountInt = Integer.parseInt(givencountString);
}
if (givencountInt <= 0 && insertcountInt <= 0){
Total = 0;
} else if (givencountInt > 0 && insertcountInt <= 0) {
Total = givencountInt;
} else if (givencountInt <= 0 && insertcountInt > 0) {
Total = insertcountInt;
} else if (givencountInt > 0 && insertcountInt > 0){
// Add Counter textView and Insert textView to an Int Total
Total = givencountInt + insertcountInt;
}
// Create an Intent to return to the mainActivity.
Intent beginPushup = new Intent(this, MainActivity.class);
// Pass the current number to the push-up Counter activity.
beginPushup.putExtra(TOTAL_DONE, Total);
// Start mainActivity.
startActivity(beginPushup);
}
TextUtils is a class provided in Android Framework.
This will check for if the content is not empty and also digits only. You can obviously omit the digit check if you are sure that only number will be the input of your edit text.
Because when your EditText is empty, it has no numerical value.
You can do
Integer.parseInt(insertcountBtn.getText().toString());
when the input is blank; there's no Integer value there, because there's nothing at all, so it's going to throw a NumberFormatException.
You can do the following to make sure it has a value (default will be 0 on failure):
int insertedcountInt;
try {
insertedCountInt = Integer.parseInt(insertcountBtn.getText().toString());
} catch (NumberFormatException e) {
insertedCountInt = 0;
}
The issue here is you are defining editText to check for only interger: you did not put the conditional statement for the cases like if String was entered, if editText is blank, it contains String. Hence, you may want to put something like;
String editTextString = String.valueOf(insertcountBtn.getText());
if (editTextString == "") {
//do something
}
Alternatively,
String editTextString = insertcountBtn.getText().toString();
if (editTextString == "") {
//do something
}
I'm trying to get different ID with for. What I have is a CardView with diferent IDs for each card and I would like to get data when clicked.
I have done this:
public void setToggleEvent(final GridLayout mainGrid) {
for ( int i = 0; i < mainGrid.getChildCount(); i++){
count = i;
final CardView cardView = (CardView)mainGrid.getChildAt(i);
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(cardView.getCardBackgroundColor().getDefaultColor() == -1) {
for (int f = 0; f < mainGrid.getChildCount(); f++){
if (f == count) {
int index = f;
String idFood = "food" + index;
int resID = getResources().getIdentifier(idFood, "id", getPackageName());
foodName = findViewById(resID);
foodName.getText();
}
}
//canvi color de fons
cardView.setCardBackgroundColor(Color.parseColor("#FF6F00"));
foodData = foodName.toString();
selectedVegetables.add(foodData);
} else {
cardView.setBackgroundColor(Color.parseColor("#FFFFFF"));
Toast.makeText(VegetablesActivity.this, "Food Selected", Toast.LENGTH_SHORT).show();
}
}
});
}
}
Each card has a ID called: food0, food1, food2....
As you can see in the code I did this to get the IDs:
String idFood = "food" + index;
int resID = getResources().getIdentifier(idFood, "id", getPackageName());
foodName = findViewById(resID);
foodName.getText();
and then:
foodData = foodName.toString();
selectedVegetables.add(foodData);
But when I run it says that foodName is null ( java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.TextView.getText()' on a null object reference)
and is in this line where the error shows up
foodName.getText();
Any idea?
Sorry for my bad english, it's not my native lenguage, hope everyone could understand this.
I surprised! this is not actually logical!
foodName = findViewById(resID);
int resID not provide you like this: "R.id.exampleId" type of id.
resID Only provide you a integer value.
I'm trying to build a calculator that subtracts one textview from another. One of the textview has a constant value 5. The other textview gets its value after a user presses buttons from 0 to 9. There's also a button for a decimal sign (dot). So, for example, if I press buttons 4, 5, ., 6 and 7, the textview will show 45.67 and a third textview will present the answer (40.67).
This example works fine. But my problem is that I want to limit the number of integers (numbers before the dot) to three. Although I can do this by simply adding setMaximumIntegerDigits to 3, it doesn't work as I'd like. For example, if I press 4, 5 and 3, the textview shows 453. That's fine. However, if I then press another number, for example 7, it shows 537. If I press 8 after that, it shows 378, and so on.
The same problem doesn't exist for decimal numbers. So, my question is, how can I set the actual integer limit so that when I press a number for the fourth time, the application wouldn't change the number in textview?
The code:
public class MainActivity extends AppCompatActivity {
private TextView textResult;
private TextView textSubtractor;
private TextView textSubtractee;
private String display = "0";
private String result = "0";
private SharedPreferences mPrefs;
Button btnDone;
double num1, num2, sub;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textResult = (TextView) findViewById(R.id.textResult);
textSubtractor = (TextView) findViewById(R.id.textSubtractor);
textSubtractee = (TextView) findViewById(R.id.textSubtractee);
btnDone = (Button) findViewById(R.id.btnDone);
textSubtractor.setText(display);
textResult.setText(result);
mPrefs = getSharedPreferences("test", 0);
if (mPrefs != null){
display = mPrefs.getString("display", "0");
sub = mPrefs.getInt(result, 0);
}
updateScreen();
btnDone.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
}
});
}
public void onClickNumber(View v) {
if (v.getId() == R.id.btnDot && (display.equals("") || display.contains("."))) {
return;
}
if ((v.getId() == R.id.btn0 ||
v.getId() == R.id.btn1 || v.getId() == R.id.btn2 ||
v.getId() == R.id.btn3 || v.getId() == R.id.btn4 ||
v.getId() == R.id.btn5 || v.getId() == R.id.btn6 ||
v.getId() == R.id.btn7 || v.getId() == R.id.btn8 ||
v.getId() == R.id.btn9) && (display.equals("0"))) {
clear();
updateScreen();
}
Button b = (Button) v;
display += b.getText();
updateScreen();
DecimalFormat df = new DecimalFormat("##.##");
df.setRoundingMode(RoundingMode.FLOOR);
df.setMaximumIntegerDigits(3);
num1 = Double.parseDouble(display);
textSubtractor.setText(df.format(num1));
num2 = Double.parseDouble(textSubtractee.getText().toString());
sub = num1 - num2;
textResult.setText(df.format(sub));
}
public void onClickClear(View v) {
clear();
}
private void clear() {
display = "";
result = "";
textSubtractor.setText("0");
textResult.setText("0");
}
private void updateScreen() {
textSubtractor.setText(display);
}
For a simple solution, I would suggest checking the integer and decimal part of the input when new numeric button is pressed:
//Class constants
final static int INTEGER_SIZE = 3;
final static int DECIMAL_SIZE = 2;
public void buttonPressed(View v) {
if (v.getId() == R.id.btn_dot){ // Handle dot
if(!display.contains("."))
display+=".";
}else{ // Only number values reach this
if(display.equals("0")){ // Handle default zero
clear();
updateScreen();
}
if(display.contains(".")){ //If the number contains a dot, decimal length has to be checked
String[] split = display.split("\\.");
if(split.length==2 && split[1].length()==DECIMAL_SIZE)
return; // New number is not added
}else if(display.length()==INTEGER_SIZE) //Otherwise check the length of the integer (whole sting)
return; // New number is not added
// New number will be added
Button b = (Button) v;
display += b.getText();
updateScreen();
DecimalFormat df = new DecimalFormat("##.##");
df.setRoundingMode(RoundingMode.FLOOR);
num1 = Double.parseDouble(display);
textSubtractor.setText(df.format(num1));
num2 = Double.parseDouble(textSubtractee.getText().toString());
sub = num1 - num2;
textResult.setText(df.format(sub));
}
}
In the long run, you should consider giving user some feedback like disabling the buttons or showing maximum length of the number on UI.
My question is: In android programming how to pass double and string data obtained in onPostExecute() method of AsyncTask to another activity that will receive this data. for example to pass double coordinates and string names, that i got in onPostExecute() method and then transfer these string data to another activity. I attach my code. Thanks in advance.
protected void onPostExecute(String result) {
super.onPostExecute(result);
String[] map = result.split("[\":,]");
int i = 64;
int a = 1;
String[] lat = new String[6000];
while (i < 5000) {
lat[a] = map[i];
i = i + 84;
a = a + 1;
}
int i2 = 76;
int a2 = 1;
String[] lng = new String[6000];
while (i2 < 5000) {
lng[a2] = map[i2];
i2 = i2 + 84;
a2 = a2 + 1;
}
int i3 = 1;
map_lat = new double[61];
while (i3 < 60) {
map_lat[i3] = Double.parseDouble(lat[i3]);
Log.i("JSON", "Lat: " + map_lat[i3]);
i3 = i3 + 1;
}
int i4 = 1;
map_lng = new double[61];
while (i4 < 60) {
map_lng[i4] = Double.parseDouble(lng[i4]);
Log.i("JSON", "Lng: " + map_lng[i4]);
i4 = i4 + 1;
}
int i5 = 40;
int a5 = 1;
map_loc = new String[6000];
while (i5 < 4950) {
map_loc[a5] = map[i5];
Log.i("JSON", "Loc: " + map_loc[a5]);
i5 = i5 + 84;
a5 = a5 + 1;
}
int i6 = 58;
int a6 = 1;
map_info = new String[6000];
while (i6 < 4950) {
map_info[a6] = map[i6];
Log.i("JSON", "Info: " + map_info[a6]);
i6 = i6 + 84;
a6 = a6 + 1;
}
double[] ab = map_lat;
double[] ac = map_lng;
String[] ad = map_loc;
String[] ae = map_info;
String af = "0";
public double[] Map(){
double[] ab = map_lat;
double[] ac = map_lng;
String[] ad = map_loc;
String[] ae = map_info;
return ab;
}
double[] ag = Map();
If you want to start a new activity, you should do what Soham said and put the data on the intent.
If you want to send the data back to the activity that started the AsyncTask, you could send a copy of that context and have the AsyncTask call a specific method at the end of the execution and send the result through that method.
A good way to get information from onPostExecute is to use an Interface.
public interface AsyncClass {
void processFinish(String[] output);
}
Then back in our MainActivity you can call this to grab the data you want.
#Overide
public void processFinish(String[] output) {
String[] temp = output;
}
And as Soham answered, you can pass this output to an intent if you need to pass it to another class.
Before asking question please google it.Have you tried that.There are tons of examples.
You can use intents, which are messages sent between activities. In a intent you can put all sort of data, String, int, etc.
In your case, in activity2, before going to activity1, you will store a String message this way :
Intent intent = new Intent(activity2.this, activity1.class);
intent.putExtra("message", message);
startActivity(intent);
In activity1, in onCreate(), you can get the String message by retrieving a Bundle (which contains all the messages sent by the calling activity) and call getDouble() on it :
Bundle bundle = getIntent().getExtras();
String message = bundle.getDouble("message");