Android Form Reset? - android

I have a simple calculator that has six EditText views where users will enter numbers to perform a simple math function. This app will satisfy a repetitive task wherein the users will enter the information, press the submit button and the answer is displayed in a separate textView.
I want to add a simple 'clear' button that will reset the form so the users can begin a new calculation and the EditText views will show their hints for user input once again.
Is there a 'reset' type function that will clear all of the form data and reload the hints or do I have to kill the app and start it again? If so, whats a good starting place for how to do this?
Thanks!

The most basic way to do this would be to simply reset your EditText views. If you have logic that drives the update of these fields, then resetting them to an empty String and requesting a "recalculation" to update the hints.
Something like this:
private void onClear()
{
EditText firstField = (EditText)this.findById(R.id.firstField);
EditText secondField = (EditText)this.findById(R.id.secondField);
//...etc...
if (firstField != null) firstField.setText("");
if (secondField != null) secondField.setText("");
updateHints();
}
private void updateHints()
{
//Logic for your "hints"
}

No, you have to implement it yourself. I suggest you create an int array with the IDs of all your EditTexts you want to reset (R.id.xyz). Then create a loop to .setText() to each of the EditTexts from the array, which you can call every time you want the fields to be cleared. Something like:
private void resetFields() {
EditText temp;
for (int i = 0; i < myEditTexts.length; i++) {
temp = (EditText) findViewById(textViews[i]);
temp.setText("");
}
}

My answer is just a better way but it still a kind of hard code. Anyone could find another way faster, please share.
protected void clearForm() {
Button btnClear = (Button) findViewById(R.id.btn_clear_text);
btnClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText temp;
final int[] txtId = new int[] {
R.id.txt_s_free_word,
R.id.txt_s_property_name,
R.id.txt_s_ad_expense_from,
R.id.txt_s_ad_expense_to,
R.id.txt_s_station
};
for (int i = 0; i < txtId.length; i++) {
temp = (EditText) findViewById(txtId[i]);
temp.setText(null);
}
}
});
}

Related

Android - deleting characters on button press

Below is the method I've coded to input numbers for a calculator. The code is fully functional and is error-free.
I'm trying to figure out how I would write a separate method called backspace to remove one character at a time from the user input.
To give an example of how onClick1 works (just to make it crystal clear what I want to do), if I entered 2+4*6 (using buttons; their onClick action linked to onClick1), then textViewCalcHistExp1 would display the text 2+4*6, and arrayList would hold the following values: [2,+,4,*,6].
I want backspace to work so that if I clicked the button (linked with the backspace method), textViewCalcHistExp1's display would now be 2+4* and arrayList would now hold the following values: [2,+,4,*].
Here is the code:
ArrayList<String> arrayList = new ArrayList<String>();
String stringInput = "";
String stringInputWithOp = "";
public String prevCalc = "";
public void onClick1 (View view) {
TextView textViewCalcHistExp1 = (TextView) findViewById(R.id.textViewCalcHistExp1);
Button button = (Button) view;
stringInput = (String) button.getText().toString();
if (!stringInput.contains("+") && !stringInput.contains("-") && !stringInput.contains("×") && !stringInput.contains("÷")) {
stringInputWithOp = stringInputWithOp+stringInput;
if (arrayList.size()>0) {
arrayList.remove((arrayList.size()-1));
}
arrayList.add(stringInputWithOp);
}
else {
arrayList.add(stringInput);
arrayList.add(stringInput);
stringInputWithOp="";
}
//This version truncates array formatting i.e. entering "2+4*6" would display "2+4*6"
textViewCalcHistExp1.setText(textViewCalcHistExp1.getText().toString()+stringInput);
//This version leaves array formatting i.e. entering "2+4*6" would display [2,+,4,*,6] ;good for debugging
//textViewCalcHistExp1.setText(arrayList.toString());
}
You could do something like this:
private void backspace() {
if (!arrayList.isEmpty()) {
// removing the last item from the ArrayList
arrayList.remove(arrayList.size() - 1);
}
String string = textViewCalcHistExp1.getText().toString();
if (string.length() > 0) {
// removing the last character from the TextView
textViewCalcHistExp1.setText(string.substring(0, string.length() - 1));
}
}
You'd also need to make textViewCalcHistExp1 an instance variable (arrayList already is), by declaring it outside onClick1().

disable button click for certain rows of buttons

I dynamically create Buttons by entering a word. If I write "met", it appears on the screen - one Button per letter. The same thing happens for the next word I enter, and it appears below the previous word --- as shown in the image above.
When I click on a Button it turns green. My question is, what is the best way to disable the clicking of a row of Buttons. Meaning, if the user clicks on the 'm' in "met" I want the user to only be able to click on the Buttons in "met" and to not be able to click on any of the Buttons in "had", "goes", or "ran"
Here is my code:
EDIT
int size = enter_txt.getText().toString().length();
for (int i=0; i<size; i++){
final Button dynamicButtons = new Button(view.getContext());
dynamicButtons.setLayoutParams(rlp);
dynamicButtons.getLayoutParams().width = 130;
dynamicButtons.getLayoutParams().height = 130;
dynamicButtons.setTag("0");
dynamicButtons.setId(1);
dynamicButtons.setText(edit_text_array[i]);
dynamicButtons.setBackgroundResource(R.drawable.button);
button_list.add(dynamicButtons);
linearLayout2.addView(dynamicButtons, rlp);
dynamicButtons.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
int i=0;
LinearLayout ll = (LinearLayout) dynamicButtons.getParent();
for(i=0; i<list_of_ll.size();i++){
if (ll == list_of_ll.get(i)){
list_of_ll.get(i).setId(i);
break;
}
}
if(list_of_ll.get(i).getId()==i)
ButtonOnClick(view);
}
});
}
linearLayout2.setId(0);
linearLayout2.setTag("0");
list_of_ll.add(linearLayout2);
EDIT
I created a List of the LinearLayouts for each row of Buttons. The Buttons turn green if the id of the LinearLayout is set to 1. When I click on a Button I want that LinearLayout to stay at 1 and have all other rows/LinearLayouts set to 0 so they become unclickable.
Currently, every Button I click turns green even if it's in a different row. Can someone please help me solve this issue?
Why you don't set Id in the for loop so that you are able to refer and set the onlicklistener to null like jpcrow already mentioned.
Set Id like:
YourCreatedBtn.setId(i+1);
//Id's setted programmatically don't.
have to be unique... But they should be
a positive number (referring to the
android documentation)
And in your on click method simply set onclicklistener for specified Id's to null. Just a hint, hope it helps
Update regarding Thread-openers Comment
I found two simple ways but i would prefer the one which is not commented out in the buttonIsClicked:
LinearLayout llrow;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
llrow = (LinearLayout) findViewById(R.id.test_layout);
//Adding 5 Buttons
for(int i = 0; i<5; i++) {
Button mybtn = new Button(this);
//set LayoutParams here
mybtn.setId(5);
mybtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
buttonIsClicked(v);
}
});
llrow.addView(mybtn);
}
}
private void buttonIsClicked(View v) {
/*ArrayList<View> myButtons = llrow.getTouchables();
for(int i = 0; i < llrow.getChildCount(); i++){
myButtons.get(i).setOnClickListener(null);
}*/
for(int i = 0; i<llrow.getChildCount(); i++){
llrow.getChildAt(i).setOnClickListener(null);
}
}
It's just a simplified Version of your code, but i'm sure you will get the Content..
What if found out is, that you don't have to set the ID in both cases.. You can easily get all the child over
YourRowLinearLayout.getChildAt(starting from 0 to n-1-Views you added)...
I didn't found a way around the for-loop... But this small-little loop will not break your neck regarding to Performance..
The outcommented-code is the second Approach, finding all the Child over getTouchables which logically leads to an ArrayList and that's exactly the reason why i don't like it. You have to initialize an arraylist...... However, this also won't break your neck regarding to Performance but a penny saved is a penny got! ;) Hope it helps and everything is clear. Both of them work! Please mark as accepted answere if it fits your Needs...
You have to distinguish between the two rows, either add them to different ViewGroups or you can use View.setTag(int key, Object tag)

Android calculator buttons

I am trying to make a calculator for Android. Here is the code for my buttons:
int[] button_ids = {
R.id.BtnNum0, R.id.BtnNum1, R.id.BtnNum2, R.id.BtnNum3, R.id.BtnNum4, R.id.BtnNum5, R.id.BtnNum6,
R.id.BtnNum7, R.id.BtnNum8, R.id.BtnNum9, R.id.BtnAdd, R.id.BtnSub, R.id.BtnDiv, R.id.BtnMult,
R.id.BtnClear, R.id.equals
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditTextValue = (EditText) findViewById(R.id.editText1);
TVValue = (TextView) findViewById(R.id.textView1);
buttons = new ArrayList<Button>();
for(int id : button_ids) {
Button button = (Button)findViewById(id);
button.setOnClickListener(this);
buttons.add(button);
}
}
How I can change this part to a block of code where I won't have to declare the IDs of the buttons? (e.g. R.id.BtnNum0)
int[] button_ids = {
R.id.BtnNum0, R.id.BtnNum1, R.id.BtnNum2, R.id.BtnNum3, R.id.BtnNum4, R.id.BtnNum5, R.id.BtnNum6,
R.id.BtnNum7, R.id.BtnNum8, R.id.BtnNum9, R.id.BtnAdd, R.id.BtnSub, R.id.BtnDiv, R.id.BtnMult,
R.id.BtnClear, R.id.equals
};
I have been searching for an answer, but I still can't find a solution.
What you can do, since this code seems to only set a single OnClickListener for all Buttons, is to do it in xml
For each Button set
android:onClick="functionName"
then in your code you can do away with all of the id's and your for loop. In Java just create a function like
public void functionName(View v)
{
switch (v.getId())
{
case R.id.buttonId:
// do work for this Button
break;
...
}
The way you are doing it is fine but this is how I prefer to handle this situation. You just have to give all of the Buttons the same function name in xml then use that name as your function name in Java. You also just have to be sure to declare the function with a void return type and make sure it takes a View as its one and only parameter as in my example.
The Button Docs also have an example of this
in your layout file add this to every button
<Button
...
android:onClick="btnClicked"
.../>
then in your code add this method and check for each button in this method
public void btnClicked(View v)
{
switch(v.getId())
{
case R.id.BtnNum0:
// your code
break;
....
}
}
That is likely the best solution unfortunately, unless you use some sort of annotation framework which still doesn't cut down much on the boilerplate.
edit:
You could try to get a pointer to whatever ViewGroup is holding the Button views and then getting all of its children, and then looping through them while casting them to Buttons as you go.
For example: If your Button objects in XML are housed in a LinearLayout, you could get the pointer to that and do something like this:
for(int i=0; i < ((ViewGroup)v).getChildCount(); ++i) {
Button nextChild = (Button) ((ViewGroup)v).getChildAt(i);
}
Of course, I recommend against this, but it is still a possibility.
As trevor-e suggested, you can give an annotation processor a try. Android Annotations can simplify your code to:
#Click
public void BtnNum0() {
// Button 0 clicked
}
#Click
public void BtnNum1() {
// Button 1 clicked
}
// etc.
If you go this route, please do try to use names following the Java convention as the button names correspond with function names.

How would I create a back button for a random generator so the previous textview is displayed?

The question really is that simple. I have an activity with a button that randomly changes the text of a textview box. How do I add another button that gathers the previous number generated so the previous textview text comes back - for a quotes app.Is there a feature I require? I have searched, but I cannot find a feature that will 'go back' on the random number generator.
Thank you in advance.
You dont need to go back on the generator itself, just remember the previous values. Store it in a variable. Here we are using prev as an array, because we need it to be final so we can access it in the anonymous inner classes (click handlers). But we also need to change it. So we use the prev[0] value.
Here I am assuming you have a button called nextNum which generates the next random number. But that could be anything, it doesnt matter. When you generate a new random number simply update the 0th element of the prev array and you should be fine.
final String[] prev = new String[] { "" }
#Override
public void onCreate(Bundle bundle) {
// ....
Button BackQuote = (Button)findViewById(R.id.back);
final TextView display = (TextView) findViewById(R.id.textView1);
// number generator button
Button nextNum = (Button) findViewById(R.id.random);
nextNum.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// generate a random number
// store it in prev
prev[0] = rndNum.toString();
}
});
BackQuote.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
display.setText(prev[0]);
}
});
}
Unless there is a specific reason you want to avoid this, then this would work perfectly fine. And there is no way to go back on a random generator. By definition it IS random! (Yes, Pseudo-random. Nonetheless)
So if you want to keep an history, you are going to have to implement those yourself. I have yet to see a random generator which has a history feature. I'd be surprised if i do too.

ParseInt Exception

I am creating a small calc app with EditText views and Im running into an runtime exception when the user leaves an EditText view empty causing the ParseInt to try and Parse nothing. Ive read that I need to 'Try' and 'Catch' this error before it occurs, but Im unsure of where and how to do this!
Any advice is much appreciated!
Here is my code:
public class HandlerExamples extends Activity implements OnClickListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button)findViewById(R.id.testButton);
button.setOnClickListener(this);
public void onClick(View v) {
String a,b,t;
double vis;
EditText txtbox1 = (EditText)findViewById(R.id.A);
EditText txtbox2 = (EditText)findViewById(R.id.B);
EditText txtbox3 = (EditText)findViewById(R.id.t);
TextView tv = (TextView) findViewById(R.id.Answer);
a = txtbox1.getText().toString();
b = txtbox2.getText().toString();
t = txtbox3.getText().toString();
vis = ((Integer.parseInt(a)*1) + (Integer.parseInt(b)*2)) / (Double.parseDouble(t));
tv.setText(double.toString(vis));
}
}
Thanks so much!
public void onClick(View v) {
int id = v.getId();
switch(id){
case R.id.xx:
//do things xx click
break;
case R.id.yy:
//do things yy click
break;
}
}
you can get the view id to know whick widget was clicked.
Changwei Yao defined one way you can do this, but here's the way most Android programmers would do this (programmatically), since it's a little easier to read and figure out what your widgets are doing:
But first, remove the implements OnClickListener from your Activity, as it's not needed.
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// what you want your button to do when clicked
}
}
editText.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// what you want your EditText to do when clicked
// (such as editText.setText(""))
}
}
Another way to do the same thing is to define android:onClick="insert_method_name_here" for the widgets that you want perform an action when clicked. In your case, in your main.xml (since that's what you're using in your Activity), you could write something like...
<Button android:id="#+id/testButton"
(other attributes you wish to apply to the button)
android:onClick="buttonAction" />
<EditText
(other attributes)
android:onClick="textAction" />
And then, in your Activity, you define the methods buttonAction(View v) and textAction(View v). Note that these methods must be public void, and must take the sole argument View v.
(One advantage of the XML method is that you don't necessarily have to define an android:id attribute for these widgets, unless you need to be able to manipulate them or extract information from them in your code (which means you will need to define an android:id for your EditText since you'll likely want the user's input))
If you only need to exclude the empty text field then hotveryspicy's solution is probably the quickest. For a secure solution: catching the NumberFormatException will filter anything that can not be converted to an integer.
int vis;
try {
vis = Integer.parseInt(a);
}
catch(NumberFormatException nfe) {
Log.e(TAG,"trying to convert:"+a+" to integer failed");
vis = 0;
}

Categories

Resources