This code creates a seekbar and makes the seekbar create as many EditText fields as the slider is at / remove ones that would be too much. This code is in OnActivityCreated
final LinearLayout linearLayout = (LinearLayout) getActivity()
.findViewById(R.id.npv_calcfields);
EditText editText = new EditText(getActivity());
editText.setId(i);
editText.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
SeekBar bar = (SeekBar) getActivity().findViewById(R.id.npv_seekbar);
final TextView selection = (TextView) getActivity()
.findViewById(R.id.npv_selected);
bar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekbar, int progress,
boolean fromUser) {
selection.setText("You have selected " + progress + " periods.");
if (progress == 0) {
String normalstring = getActivity().getResources()
.getString(R.string.npv1);
selection.setText(normalstring);
}
if (i > progress) {
while (i > progress) {
i--;
EditText editText = (EditText) getActivity()
.findViewById(i);
linearLayout.removeView(editText);
}
} else {
while (i < progress) {
EditText editText = new EditText(getActivity());
editText.setId(i);
editText.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
linearLayout.addView(editText);
editText.setHint("Cash Flow " + i);
i++;
}
}
}
public void onStopTrackingTouch(SeekBar arg0) {
}
public void onStartTrackingTouch(SeekBar arg0) {
}
});
This code is in the general class area:
int i = 0;
EditText r = (EditText) getActivity().findViewById(R.id.npv_rate);
Button calc = (Button) getActivity().findViewById(R.id.npv_calc);
EditText[] DynamicField = new EditText[16];
Now I want users to input numbers into those edittext fields and then I want to do some math on them: Entry / (Math.pow(1+r, i) with i beeing the id of the field. The first entry should therefore be calculated as this: entry/(1+r)^0. This is what I tried but it doesn't work. It just crashes on startup.
calc.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Double r1 = Double.parseDouble(r.getText().toString());
EditText editText = (EditText) getActivity().findViewById(i);
TextView answer = (TextView) getActivity().findViewById(R.id.npv_answer);
double[] CashFlows;
CashFlows = new double[i];
double result = 0;
CashFlows[i] = (Double.parseDouble(editText.getText()
.toString())) / (Math.pow(1 + r1, i));
for (double d : CashFlows) {
result += d;
}
answer.setText("answer is " + result);
}
});
What did I do wrong? by the way only the last code segment isnt working. if i comment that out it all works fine i tested it :) just dosent do anything obviuosly :)
ok a little background on the errorlog that you can see here: http://pastebin.com/G8iX6Pkm
EDIT: the entire class file can be seen here: http://pastebin.com/dxA91dst, the entire project can be found here: https://github.com/killerpixler/Android-Financial-Calculator.git
the class file is a fragment that gets loaded in a DetailsActivity when somebody clicks on a listitem from the Main activity. Like i said the error has to be in the button listener because it was working before i added it.
That NullPointerException comes from the fact that you initialize your Views using the getActivity() method where you declare them as fields in the F_NPV class. The method getActivity() method will return a valid Activity reference after the callback onAttach() is called, so the way you initialize the views will not work as, at that moment(when the fields of the Fragment class are initialized) the method getActivity will return null, no valid reference. The correct way to do that initialization is doing it in the onActivityCreated callback:
EditText r;
Button calc;
//...
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
r = (EditText) getActivity().findViewById(R.id.npv_rate);
calc = (Button) getActivity().findViewById(R.id.npv_calc);
//...
Also, if I may, some suggestions regarding your code:
You're doing some double's parsing from Strings and it may be a good idea to check the input so you don't throw a NumberFormatException. For example, if the user creates some EditTexts and then clicks the calculate Button(I know, it sounds silly, but there are chances the user will do it(I did it for example)), you'll throw a NumberFormatException as you try to parse an empty String. Instead make a little check:
public void onClick(View arg0) {
Double r1 = Double.parseDouble((r.getText().toString())
.equals("") ? "0" : r.getText().toString());
EditText editText = (EditText) getActivity().findViewById(i);
TextView answer = (TextView) getActivity().findViewById(R.id.npv_answer);
double[] CashFlows;
CashFlows = new double[i];
double result = 0;
String tmp = editText.getText().toString();
CashFlows[i] = (Double.parseDouble(tmp.equals("") ? "0" : tmp))
/ (Math.pow(1 + r1, i));
//...
Also, even if you have correct values in the EditText the above code will throw a NullPointerException, as the editText variable will be null. The reason for this is in the while loops that you used to create the fields. For example, if the user moves the SeekBar to 3 than the while loop will run 3 times, each time incrementing the i value. So i will be 0, 1, 2, so far correct but because you increment i each time the final i will be 4. Now in the onClick method you'll look for an EditText with the id i, but as there is no EditText in the layout with the id 4, the view will be null.
Also, try to give your classes better names, you may know very well what they mean but you could be making things worse for someone that reads your code(like F_PNV, F_PV etc).
Code for the onActivityCreated method. This should solve what you're trying to do(if I understand what you want):
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
r = (EditText) getActivity().findViewById(R.id.npv_rate);
calc = (Button) getActivity().findViewById(R.id.npv_calc);
final LinearLayout linearLayout = (LinearLayout) getActivity()
.findViewById(R.id.npv_calcfields);
SeekBar bar = (SeekBar) getActivity().findViewById(R.id.npv_seekbar);
final TextView selection = (TextView) getActivity().findViewById(
R.id.npv_selected);
bar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekbar, int progress,
boolean fromUser) {
selection
.setText("You have selected " + progress + " periods.");
if (progress == 0) {
String normalstring = getActivity().getResources()
.getString(R.string.npv1);
selection.setText(normalstring);
linearLayout.removeAllViews(); // the progress is 0 so
// remove all the views that
// are currently present
} else {
int currentChilds = linearLayout.getChildCount();
if (currentChilds < progress) {
while (currentChilds != progress) {
EditText editText = new EditText(getActivity());
editText.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
linearLayout.addView(editText);
currentChilds++;
}
} else if (currentChilds > progress) {
while (currentChilds != progress) {
linearLayout.removeViewAt(linearLayout
.getChildCount() - 1);
currentChilds--;
}
}
}
}
public void onStopTrackingTouch(SeekBar arg0) {
}
public void onStartTrackingTouch(SeekBar arg0) {
}
});
calc.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
Double r1 = Double.parseDouble((r.getText().toString())
.equals("") ? "0" : r.getText().toString());
TextView answer = (TextView) getActivity().findViewById(
R.id.npv_answer);
final LinearLayout linearLayout = (LinearLayout) getActivity()
.findViewById(R.id.npv_calcfields);
int size = linearLayout.getChildCount();
double[] CashFlows = new double[size];
double result = 0;
for (int i = 0; i < size; i++) {
EditText editText = (EditText) linearLayout.getChildAt(i);
String tmp = editText.getText().toString();
CashFlows[i] = (Double.parseDouble(tmp.equals("") ? "0"
: tmp)) / (Math.pow(1 + r1, i));
}
for (double d : CashFlows) {
result += d;
}
answer.setText("answer is " + result);
}
});
}
Related
I want to make button which will call two function on click I am using this code currently but when I click it on 3rd time nothing happens and I want to do vice versa like when user click on button 3rd time it will call count 1 again.. this code is currently I am using
#Override
public void onClick(View v) {
clickcount=clickcount+1;
if(clickcount==1)
{
Random i = new Random ();
int c= i.nextInt(7-1) + 1;
bck.setBackgroundColor(Color.BLACK);
TextView textresult = (TextView) findViewById(R.id.textView);
textresult.setTextColor(Color.WHITE);
}
else
{
Random i = new Random ();
int c= i.nextInt(7-1) + 1;
bck.setBackgroundColor(Color.WHITE);
TextView textresult = (TextView) findViewById(R.id.textView);
textresult.setTextColor(Color.BLACK);
}
}
Hello mate Please do like this
clickcount=0;
#Override
public void onClick(View v) {
clickcount = clickcount + 1;
if(clickcount%2 == 1) {
Random i = new Random ();
int c = i.nextInt(7 - 1) + 1;
bck.setBackgroundColor(Color.BLACK);
TextView textresult = (TextView) findViewById(R.id.textView);
textresult.setTextColor(Color.WHITE);
} else {
Random i = new Random ();
int c = i.nextInt(7 - 1) + 1;
bck.setBackgroundColor(Color.WHITE);
TextView textresult = (TextView) findViewById(R.id.textView);
textresult.setTextColor(Color.BLACK);
}
}
Another solution with boolean:
boolean check = true;
#Override
public void onClick(View v) {
Random i = new Random ();
TextView textresult = (TextView) findViewById(R.id.textView);
int c= i.nextInt(7-1) + 1;
bck.setBackgroundColor(check ? Color.BLACK : Color.WHITE);
textresult.setTextColor(check ? Color.WHITE : Color.BLACK);
check = !check;
}
Or if you want two functions:
boolean check = true;
#Override
public void onClick(View v) {
if(check) {
// first function
} else {
// second function
}
check = !check;
}
I am a beginner Android developer and I have a runtime error in my code: when I want to run it in a emulator or a device it show "force close" massage. My log is here:
http://upir.ir/934/1_5e07a.jpg
My Java code:
public class Third extends Activity
{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button d = (Button) findViewById(R.id.btn4);
d.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
dialog();
}
});
}
public void dialog(){
final Dialog dialog = new Dialog(Third.this);
dialog.setContentView(R.layout.dialog);
dialog.setTitle("واحد عدد وارد شده را انتخاب کنید");
dialog.show();
RadioGroup rg = (RadioGroup) dialog.findViewById(R.id.rg);
final RadioButton rb1 = (RadioButton) dialog.findViewById(R.id.rb1);
final RadioButton rb2 = (RadioButton) dialog.findViewById(R.id.rb2);
rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup arg0, int arg1) {
if(rb1.isChecked()) {
dialog.dismiss();
Button t = (Button)findViewById(R.id.btn5);
t.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
EditText ft1 = (EditText)findViewById(R.id.f3);
TextView foot = (TextView)findViewById(R.id.foot);
TextView mile = (TextView)findViewById(R.id.mile);
TextView inch = (TextView)findViewById(R.id.inch);
TextView yard = (TextView)findViewById(R.id.yard);
TextView mm = (TextView)findViewById(R.id.millymeter);
TextView dm = (TextView)findViewById(R.id.decimeter);
TextView mim = (TextView)findViewById(R.id.micrometer);
TextView nm = (TextView)findViewById(R.id.nanometer);
TextView hand = (TextView)findViewById(R.id.hand);
TextView iron = (TextView)findViewById(R.id.iron);
TextView point = (TextView)findViewById(R.id.point);
if(ft1.getText().toString().length() == 0 ){return;}
int first = Integer.parseInt(ft1.getText().toString());
double equal = first *0.0328;
DecimalFormat formatf = new DecimalFormat("#.####");
String x = formatf.format(equal)+" فوت";
foot.setText(x);
first = Integer.parseInt(ft1.getText().toString());
equal = first * 0.000005;
DecimalFormat formatm = new DecimalFormat("#.####");
x = formatm .format(equal)+"مایل";
mile.setText(x);
equal = first * 0.393;
DecimalFormat formati = new DecimalFormat("#.####");
x = formati.format(equal)+"اینچ";
inch.setText(x);
equal = first * 0.0109;
DecimalFormat formaty = new DecimalFormat("#.#####");
x = formaty.format(equal)+"یارد";
yard.setText(x);
equal = first / 10;
DecimalFormat formatmi = new DecimalFormat("#.##");
x = formatmi.format(equal)+"دسی متر";
dm.setText(x);
int equalmm = first * 10;
x = equalmm+"میلی متر";
mm.setText(x);
int equalm = first * 10000;
x = equalm+"میکرو متر";
mim.setText(x);
int equaln = first * 10000000;
x = equaln + "نانو متر";
nm.setText(x);
equal = first * 0.098;
DecimalFormat formath = new DecimalFormat("#####.#####");
x = formath.format(equal)+"هَند";
hand.setText(x);
equal = first * 19;
x = equal+"آیرون";
iron.setText(x);
equal = first * 28;
x = equal+"پوینت";
point.setText(x);
}
});
}
You need to inflate your activity with a layout resource first before you can use the findViewById() method to retrieve views. If there's no layout, then there are no views which could possibly be found.
You are missing an important part. You need to add a view to your Activity in order to find the elements of that view like the Button you are trying to instantiate.
In your OnCreate method add this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.the_xml_file); //Here add the xml file with the view you want to show
Button d = (Button) findViewById(R.id.btn4);
d.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
dialog();
}
});
}
After your super.onCreate(savedInstanceState); are you setting the content view?
e.g.
setContentView(R.layout.nameofxmlfilehere);
In an android app I intend to allow users to answer a random sum then a new one appears on screen. This is repeated 10 times and then a final score will then be given. However I am unsure how to update the sum so that after each each a new random is shown on screen.
Below is my current code:
public class Test extends Activity {
//declare vars
TextView text;
EditText answer;
Button submit;
int random1;
int random2;
String question;
int correctAnswer;#
Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
// initialising variables
initialiseVars();
//set up random
setUpRandom();
//Set text view equal to question
text.setText(question);
//updateQuestion?
}
public void initialiseVars() {
text = (TextView) findViewById(R.id.tvTopRandomTest);
answer = (EditText) findViewById(R.id.etEnterAnswerRandomTest);
submit = (Button) findViewById(R.id.btnSubmitRandomTest);
}
public void setUpRandom() {
//setting up randoms
Random random = new Random();
// Generating random number between 1 and 12
random1 = random.nextInt(12) + 1;
// Generating another random number between 1 and 12
random2 = random.nextInt(12) + 1;
question = random1 + " x " + random2 + " = ";
correctAnswer = random1 * random2;
}
public void updateQuestion() {
//CODE TO UPDATE QUESTION
}
}
Add Button ClickListener so that when user press submit button it will update question and clean all previous values
submit = (Button) findViewById(R.id.btnSubmitRandomTest);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
updateQuestion();
}
}
Maintain a count in your activity and increase it in updateQuestion
public void updateQuestion() {
if (Int.parseString(answer.getText().toString()) != correctAnswer) {
// Show toast or something
return;
}
tries++;
if (tries == 10) return; // or do something else;
answer.setText("");
setUpRandom();
text.setText(question); // add this line in your setUpRandom();
}
To generate random integers look at this. Hopefully this will help you out.
public class Main extends Activity implements OnClickListener {
TextView ePrice;
TextView InputPrice;
TextView InputPercent;
TextView ePercent;
private SeekBar volumeControl = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
/** Remove title bar */
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/** Hide Auto Keyboard */
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
/** Hide Auto Keyboard End here */
InputPrice = (TextView) findViewById(R.id.ePrice);
InputPercent = (TextView) findViewById(R.id.ePercents);
ePrice = (TextView) findViewById(R.id.ePrice);
ePercent = (TextView) findViewById(R.id.ePercents);
Here is my SeekBar. Before this SeekBar I have been using EditText and every thing was ok but after i started using this SeekBar the SECOND result is so weird!!
SeekBarPer = (SeekBar) findViewById(R.id.volume_bar);
SeekBarPer.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
int progressChanged = 0;
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser){
progressChanged = progress;
TextView label = (TextView) findViewById(R.id.ePercents);
label.setText(""+progressChanged);
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
what I have:
One EditText up One TextView under the SeekBar and Two another TextView are down to show the result of calculating the Price and the Percent! The First result is going well but the second is NOT!
For example if i calculate 30 dollars minus 50% i got the first result 15 and the second one 35.
What I want:
Just to correct the second result
Here is the Calculation:
// show the price to get
final TextView tR = (TextView) findViewById(R.id.viewResult);
// show the price to pay
final TextView tRpay = (TextView) findViewById(R.id.viewResultPay);
Button buttonConvert = (Button) findViewById(R.id.buttonConvert);
buttonConvert.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
double price = Double.parseDouble(ePrice.getText().toString());
double percent = Double.parseDouble(ePercent.getText().toString());
double pri = (price / 100.0f) * percent;;
double per = percent * ((100.0f - price)/100.0f);
tR.setText(String.valueOf(pri));
tRpay.setText(String.valueOf(per));
tR.setText("" + pri);
tRpay.setText("" + per);
// catch
} catch (NumberFormatException ex) {
// write a message to users
tR.setText("");
}
}
});
}
Update:
I am using the SeekBar as a percent. So when I move the SeekBar there will be numbers 0-100 in the second TextView.
Thanks in advance!
This should be what you want:
DiscountValue = price*discount/100.0f;
ValueToPay = price - DiscountValue;
I hope this isn't a stupid question. I'm having some trouble clearing a TextView. I've looked around and everyone keeps saying use: textView.setText(""); in onCreate but doesn't seem to work for some reason. Basically, my app just accepts a number from an editText then runs the Fibonacci sequence (when a button is clicked) and displays the result in a textView. Well, the sequence displays fine but I want the textview to clear every time I click the button - so far it just keeps adding more text to what's already there.
Am I placing textView.setText(""); in the wrong location? Or am I just missing some other concept? (I also tried placing it from my OnClick - that didn't work either).
Here is my code:
public class MainActivity extends Activity {
// primary widgets
private EditText editText;
private TextView textView;
private Button button1;
static ArrayList<Integer> fibList = new ArrayList<Integer>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText1);
textView = (TextView) findViewById(R.id.textView2);
button1 = (Button) findViewById(R.id.button1);
//Attempt to clear TextView
textView.setText("");
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String input = editText.getText().toString();
int number = Integer.parseInt(input);
int tmp = 0;
// confirm input
if (number < 20) {
Toast.makeText(getApplicationContext(),
"You entered: " + number, Toast.LENGTH_LONG).show();
for (int i = 0; i <= number; i++) {
fibList.add(fib(i));
// sum even numbers
if (fib(i) % 2 == 0) {
tmp += fib(i);
}
}
} else {
Toast.makeText(getApplicationContext(),
"Number is too Large: " + number, Toast.LENGTH_LONG)
.show();
}
String array = fibList.toString();
textView.setText(array);
}
});
}
// run fibonacci sequence
public static int fib(int n) {
if (n < 2) {
return n;
} else {
return fib(n - 1) + fib(n - 2);
}
}
#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;
}
}
If you want the TextView to clear on each button click then the .setText must go in you onClick. The reason you would put the .setText in your onCreate is to clear the text as soon as your activity is created, but you do not have anything to clear just yet since your button has not yet been pushed so setText will do nothing. Also, since your onCreate will only run once for your activity, it will never go back to the setText again. Try the following:
public class MainActivity extends Activity {
// primary widgets
private EditText editText;
private TextView textView;
private Button button1;
static ArrayList<Integer> fibList = new ArrayList<Integer>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText1);
textView = (TextView) findViewById(R.id.textView2);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textView.setText(""); //Clear the TextView
fibList.clear(); //Clear your array list before adding new elements
String input = editText.getText().toString();
int number = Integer.parseInt(input);
int tmp = 0;
// confirm input
if (number < 20) {
Toast.makeText(getApplicationContext(),
"You entered: " + number, Toast.LENGTH_LONG).show();
for (int i = 0; i <= number; i++) {
fibList.add(fib(i));
// sum even numbers
if (fib(i) % 2 == 0) {
tmp += fib(i);
}
}
} else {
Toast.makeText(getApplicationContext(),
"Number is too Large: " + number, Toast.LENGTH_LONG)
.show();
}
String array = fibList.toString();
textView.setText(array);
}
});
}
// run fibonacci sequence
public static int fib(int n) {
if (n < 2) {
return n;
} else {
return fib(n - 1) + fib(n - 2);
}
}
#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;
}
}
you will need to clear textView on Button click event before adding new results to it.do it as:
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
textView.setText(""); //<<<<<< clear TextView on Button Click
.....
The problem is more likely in fibList that is not being cleared