i try to get the the value of the text from the EditText as an integer number , but i found that every time i insert any value it calculate the initialized value from the catch , so what's the solved for this problem
the result become =0
public Button bu,bu2,bu3,bu4,bu5;
int num=0,num2=0,num3=0,result=0;
public EditText on,on2,on3,on4;
public TextView tex ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_monthlycalc);
bu=(Button)findViewById(R.id.year);
bu.setOnClickListener(this);
bu2=(Button)findViewById(R.id.calc);
bu2.setOnClickListener(this);
bu3=(Button)findViewById(R.id.reset);
bu3.setOnClickListener(this);
bu4=(Button)findViewById(R.id.H1);
bu4.setOnClickListener(this);
bu5=(Button)findViewById(R.id.ron);
bu5.setOnClickListener(this);
try {
on=(EditText)findViewById(R.id.loanAm);
num=Integer.valueOf(on.getText().toString().trim());
} catch (NumberFormatException e) {
num=0;
}
try {
on2=(EditText)findViewById(R.id.intRate);
num2=Integer.valueOf(on2.getText().toString().trim());
} catch (NumberFormatException e) {
num2=0;
}
try {
on3=(EditText)findViewById(R.id.lonTerm);
num=Integer.valueOf(on3.getText().toString().trim());
} catch (NumberFormatException e) {
num3=0;
}
tex = (TextView) findViewById(R.id.monPay);
result=num+num2+num3;
#Override
public void onClick(View v)
{
if (v.getId()==R.id.calc)
tex.setText(String.valueOf(result));
}
Move your code to onClick
You are trying to get the values inside onCreate which happens while the activity is being launched and all EditTexts are empty, put it inside the onClick and it will work :)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_monthlycalc);
bu=(Button)findViewById(R.id.year);
bu.setOnClickListener(this);
bu2=(Button)findViewById(R.id.calc);
bu2.setOnClickListener(this);
bu3=(Button)findViewById(R.id.reset);
bu3.setOnClickListener(this);
bu4=(Button)findViewById(R.id.H1);
bu4.setOnClickListener(this);
bu5=(Button)findViewById(R.id.ron);
on=(EditText)findViewById(R.id.loanAm);
on2=(EditText)findViewById(R.id.intRate);
on3=(EditText)findViewById(R.id.lonTerm);
tex = (TextView) findViewById(R.id.monPay);
}
#Override
public void onClick(View v)
{
try {
num=Integer.valueOf(on.getText().toString().trim());
} catch (NumberFormatException e) {
num=0;
}
try {
num2=Integer.valueOf(on2.getText().toString().trim());
} catch (NumberFormatException e) {
num2=0;
}
try {
num=Integer.valueOf(on3.getText().toString().trim());
} catch (NumberFormatException e) {
num3=0;
}
result=num+num2+num3;
if (v.getId()==R.id.calc)
tex.setText(String.valueOf(result));
}
Because you have maybe Chars or Whitespaces in your String which are not numeric.
Parse it using regex.
final Pattern pattern = Pattern.compile("\\d+"); // the regex
final ArrayList<Integer> ints = new ArrayList<Integer>(); // results
while (matcher.find()) { // for each match
ints.add(Integer.parseInt(matcher.group())); // convert to int
}
If you really want to remove all whitespaces dont use trim. Use
st.replaceAll("\\s+","")
which removes all tabs aswell
And make sure that your values are grabbed when you click the button, not before, since it dont have any values inside while initializing, if you dont define a defaultValue.
Related
I have a listview in my activity with a textview and an edittext of inputType number, the user will enter numbers in each edit text.There is a textview which displays the sum of all the numbers entered. How do i calculate the sum and show it in the textview as soon as the user enters the amount.
I tried it this way :
holder.tvDonationAmount.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View view, boolean b) {
try {
amount = Integer.parseInt(holder.tvDonationAmount.getText().toString());
} catch (NumberFormatException e) {
e.printStackTrace();
}
addn_array.add(amount);
for (int j = 0; j < addn_array.size(); j++) {
try {
sum += addn_array.get(j);
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
}
});
I tried adding each element after he's entered the number into an Arraylist of Integers and add the elements which throws the error.
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference
at the line inside for loop sum+ = . .
I also implemented this in my Textwatcher like this
private TextWatcher watcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
try {
amount = Integer.parseInt(holder.tvDonationAmount.getText().toString());
addn_array.add(amount);
} catch (NumberFormatException e) {
e.printStackTrace();
}
Toast.makeText(context, ""+addn_array.get(0), Toast.LENGTH_SHORT).show();
for (int j = 0; j <addn_array.size(); j++) {
try {
sum += addn_array.get(j);
Toast.makeText(context, ""+sum, Toast.LENGTH_SHORT).show();
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
Toast.makeText(context, "" + sum, Toast.LENGTH_SHORT).show();
}
};`
It throws this error.
[![Logcat][1]][1]
Can you please tell me what's wrong with this or can you please suggest any better way if there's any?
Take a look at TextWatchers. You don't need a focus change listener, but a TextWatcher, since it listens to changes you make to the text inside the EditText.
Here is a great example: http://stacktips.com/tutorials/android/android-textwatcher-example
The problem is that in case a NumberFormatException is thrown when parsing amount, amount can be null. Thus, null is added to the list.
try {
amount = Integer.parseInt(holder.tvDonationAmount.getText().toString());
addn_array.add(amount);
} catch (NumberFormatException e) {
e.printStackTrace();
}
This will solve your NullPointerException.
Please do use a TextWatcher like #Gregorio Palamà suggested.
I have a Calendar activity. When the user selects a date, I would like the TextView under the calendar to display all events the user has stored for that date. Under the TextView is a button that takes the user to the activity where they create the event. The button on the Event Creation Activity uses fileOutputStream to save a txt file containing entered information. My issue is reading that info into the TextView on the Calendar Activity. I have the code written for the read, but when I try to point it to the directory created by the fileOutput on EventCreateActivity, I get an error "EventCreateActivity is not an enclosing class." I believe it is an enclosing class, as it has nested classes, correct? What can I do here that requires the least amount of restructuring?
Here is my CalendarActivity:
public class CalendarActivity extends AppCompatActivity {
CalendarView calendar;
Button createEvent;
public static String createEventDate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calendar);
calendar = (CalendarView)findViewById(R.id.calendar);
calendar.setOnDateChangeListener(new CalendarView.OnDateChangeListener(){
#Override
public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth){
createEventDate = (month+"."+dayOfMonth+"."+year);
createEvent.setText("Create Event for "+createEventDate);
File directory = EventCreateActivity.this.getFilesDir().getAbsoluteFile();
File[] dateFile = directory.listFiles();
if (dateFile.length > 0){
fillEventList();
}else{
noEventToday();
}
}
});
createEvent = (Button)findViewById(R.id.eventCreateButton);
createEvent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent toEventCreateActivity = new Intent(CalendarActivity.this, EventCreateActivity.class);
startActivity(toEventCreateActivity);
}
});
}
public void fillEventList (){
TextView eventList = (TextView)findViewById(R.id.eventList);
try {
String message = createEventDate;
FileInputStream fileInput = openFileInput(message);
InputStreamReader inputStreamReader = new InputStreamReader(fileInput);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuffer stringBuffer = new StringBuffer();
while ((message = bufferedReader.readLine())!=null){
stringBuffer.append(message+"/n");
}
eventList.setText(stringBuffer.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void noEventToday(){
TextView eventList = (TextView)findViewById(R.id.eventList);
eventList.setText("Nothing scheduled for today.");
}
}
here is my EventCreateActivity:
public class EventCreateActivity extends AppCompatActivity {
String textViewText = CalendarActivity.createEventDate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_create);
TextView titleTextView = (TextView)findViewById(R.id.titleTextView);
titleTextView.setText("Create event for "+textViewText);
Button createEventButton = (Button)findViewById(R.id.saveEvent);
createEventButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
buttonSaves();
Intent toCalendarActivity = new Intent(EventCreateActivity.this, CalendarActivity.class);
EventCreateActivity.this.startActivity(toCalendarActivity);
}
});
}
public void buttonSaves () {
TimePicker timePicker = (TimePicker)findViewById(R.id.timePicker);
EditText entryEvent = (EditText)findViewById(R.id.entryEvent);
EditText entryLocation = (EditText)findViewById(R.id.entryLocation);
EditText entryCrew = (EditText)findViewById(R.id.entryCrew);
final String timeHour = timePicker.getCurrentHour().toString();
final String timeMinute = timePicker.getCurrentMinute().toString();;
final String event = entryEvent.getText().toString();
final String location = entryLocation.getText().toString();
final String crew = entryCrew.getText().toString();
try{
FileOutputStream saveNewEvent1 = openFileOutput(textViewText, MODE_WORLD_READABLE);
OutputStreamWriter saveNewEvent2 = new OutputStreamWriter(saveNewEvent1);
try {
saveNewEvent2.write(timeHour);
} catch (IOException e) {
e.printStackTrace();
}
try {
saveNewEvent2.write(timeMinute);
} catch (IOException e) {
e.printStackTrace();
}
try {
saveNewEvent2.write(event);
} catch (IOException e) {
e.printStackTrace();
}
try {
saveNewEvent2.write(location);
} catch (IOException e) {
e.printStackTrace();
}
try {
saveNewEvent2.write(crew);
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getBaseContext(), "Roger Roger", Toast.LENGTH_LONG).show();
}catch(FileNotFoundException e){
e.printStackTrace();
}
Log.i("info","The event is: "+timeHour+timeMinute+event+location+crew);
}
}
So I am new to Java and android development. So far I have been creating an app that is able to connect and interface with an arduino. I have a method that is able to read the data from the arduino (in bytes ) and then print the data as a string in UTF-8....However, I simply want this method to read and interpret the data, and have the interpreted data to be callable from another method, say button from android. Following is code that reads the data.
public class MainActivity extends AppCompatActivity {
public final String Action_USB_Permission = "com.example.myapplication.USB_PERMISSION";
UsbManager usbManager;
UsbDevice device;
UsbSerialDevice serial;
UsbDeviceConnection connection;
String data;
String adata;
TextView textView;
Button tempButton
UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() {
#Override
public void onReceivedData(byte[] arg0) {
try {
data = new String(arg0, "UTF-8"); //edit (removed String in "String data =" )
} catch (UnsupportedEncodingException e) {
e.getStackTrace();
}
}
};
// Serial codes and commands
public void pushcmd(String command) { //command for serial
serial.write(command.getBytes());
}
public void gettemp() {
pushcmd("T\n");
serial.read(mCallback);
adata = data;
}
//This is for the app creation i think
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
usbManager = (UsbManager) getSystemService(this.USB_SERVICE);
tempButton = (Button) findViewById(R.id.buttontemp);
}
public void onClickTemp(View view) { //This is the command to print data
gettemp();
tvAppend(textView, "\n Measured temperature \n" + adata);
}
private void tvAppend(TextView tv, CharSequence text) {
final TextView ftv = tv;
final CharSequence ftext = text;
runOnUiThread(new Runnable() {
#Override
public void run() {
ftv.append(ftext);
}
});
}
}
tvAppend is a method that prints the string on a textview on the screen.
I got the libraries from https://github.com/felHR85/UsbSerial and it says to simply reference it with
serial.read(mcallback), I have tried the command, but I receive a "measured temperaturenull" then the measurement is printed after, which is from the onReceivedData method . Any suggestions would be greatly appreciated.Or if I'm not clear, let me know, I'll try to clear things up some more.
Edit: I added my tvAppend method, defined a textview field and a button. I am also pointing out that I don't have the whole program included, I followed the implementation from all about circuits http://www.allaboutcircuits.com/projects/communicate-with-your-arduino-through-android/ Thanks again for the feedback
COMMENT about edit: when the code is changed to how it is above. the adata is not displayed, only "Measured temperature".
I think you're confusing yourself with the flow of data here.
You click a button on the app
It calls pushcmd to the Arduino
The Arduino sends some data back at some unknown point in the future
You read that data and update the TextView
Now, with that logic, the code could be structured like so. (Feel free to re-organize back into your app how you want).
public void onClickTemp(View view) {
gettemp();
// No value of "adata" or "data" is guaranteed here
}
public void gettemp() {
pushcmd("T\n");
serial.read(mCallback); // asynchronous callback
// No value of "adata" or "data" is guaranteed here, either
}
UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() {
#Override
public void onReceivedData(byte[] arg0) {
try {
// Here, you are guaranteed some data
String data = new String(arg0, "UTF-8");
tvAppend(textView, "\n Measured temperature \n" + data);
} catch (UnsupportedEncodingException e) {
e.getStackTrace();
}
}
};
Or, if you want to fold that all into one method, then
public void onClickTemp(View view) {
pushcmd("T\n");
serial.read(new UsbSerialInterface.UsbReadCallback() {
#Override
public void onReceivedData(byte[] arg0) {
try {
// Here, you are guaranteed some data
String data = new String(arg0, "UTF-8");
tvAppend(textView, "\n Measured temperature \n" + data);
} catch (UnsupportedEncodingException e) {
e.getStackTrace();
}
}
});
}
I'm trying to build an app which displays fun facts from a text file. To do this I get a random number and then display that specific line number from the file.When I run the app and try and press the button all I get is a blank text field. Here is my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fun_facts);
// Declare and assign variables
final TextView factLabel = (TextView) findViewById(R.id.factTextView);
Button showFactButton = (Button) findViewById(R.id.showFactButton);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
/*
code here runs when button click is detected by line 29
code shows new fact
*/
String fact = "";
//get a random number to select a fact
Random randomNumberGenrator = new Random();//construct random object
int randomNumber = randomNumberGenrator.nextInt(391);
FileReader fr = null;
try {
fr = new FileReader("facts.txt ");//construct filereader and assign file
} catch (FileNotFoundException e) {
e.printStackTrace();//exception raised
}
LineNumberReader getFact = new LineNumberReader(fr);//construct lineNumberReader
getFact.setLineNumber(randomNumber);//set current line number to random number
try {
fact = getFact.readLine();//read current line and assign it to fact
} catch (IOException e) {
e.printStackTrace();
}
factLabel.setText(fact);
try {
getFact.close();//close lineReader
} catch (IOException e) {
e.printStackTrace();
}
try {
fr.close();//close fileReader
} catch (IOException e) {
e.printStackTrace();
}
}
};
showFactButton.setOnClickListener(listener);
}
Do you getting any errors?
check this line, maybe its typo but worth check it and remove that space from path.
OLD:
fr = new FileReader("facts.txt ");
NEW:
fr = new FileReader("facts.txt");
Everything works with no errors, but in the xml, tvfinalgrade stays 0.0... Why isn't the double fin being displayed? I'm sure about what order the tvfin code lines should be written, but I'm assuming its not right.
public class GFActivity extends Activity {
public double fin;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.getfinal);
double q1, q2, ex;
EditText etq1, etq2, eteg;
etq1 = (EditText)findViewById(R.id.editText1);
try{
q1 = Double.parseDouble(etq1.getText().toString());
} catch (NumberFormatException e) {
q1=0;
}
etq2 = (EditText)findViewById(R.id.editText2);
try{
q2 = Double.parseDouble(etq2.getText().toString());
} catch (NumberFormatException e){
q2 = 0;
}
eteg = (EditText)findViewById(R.id.editText3);
try{
ex = Double.parseDouble(eteg.getText().toString());
} catch (NumberFormatException e){
ex = 0;
}
fin = 0.4*q1+0.4*q2+0.2*ex;
if(fin == (int)fin){
System.out.println((int)fin);
}
else{
fin = 0.01*((int)(fin*100));
System.out.println(fin);
}
Button solve = (Button)findViewById(R.id.getfinbutton);
solve.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
TextView tvfin= TextView)findViewById(R.id.tvfinalgrade);
tvfin.setText(fin+"");
}
});
}
}
When you start the app, in the onCreate() you already parse the EditText content(which are empty, so you throw NumberFormatException and your fin variable ends up as 0) and when you get to the part of setting the result(the user clicks the Button) you set the fin which is currently 0 to the TextView(the problem is that when the user clicks the Button you never get the current EditText content to do any calculation and the fin variable is the old value(0)). Move your calculation in the onClick() method:
Button solve = (Button)findViewById(R.id.getfinbutton);
solve.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
double q1, q2, ex;
EditText etq1, etq2, eteg;
etq1 = (EditText)findViewById(R.id.editText1);
try{
q1 = Double.parseDouble(etq1.getText().toString());
} catch (NumberFormatException e) {
q1=0;
}
etq2 = (EditText)findViewById(R.id.editText2);
try{
q2 = Double.parseDouble(etq2.getText().toString());
} catch (NumberFormatException e){
q2 = 0;
}
eteg = (EditText)findViewById(R.id.editText3);
try{
ex = Double.parseDouble(eteg.getText().toString());
} catch (NumberFormatException e){
ex = 0;
}
fin = 0.4*q1+0.4*q2+0.2*ex;
if(fin == (int)fin){
System.out.println((int)fin);
}
else{
fin = 0.01*((int)(fin*100));
System.out.println(fin);
}
TextView tvfin= TextView)findViewById(R.id.tvfinalgrade);
tvfin.setText(fin+"");
}
});