My code doesn't properly change the TextView - java

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+"");
}
});

Related

ArrayList size 0 after deserialisation Android Studio Java

Hello I tried to make an app for displaying quote in Android Studio.
But I got stuck when reading.
I created an "ArrayList" with my custom class Quotes.
I seems to work ok when writing the ArrayList to the file, but when reading from it the size of ArrayList is 0.
public class SaveQuote extends AppCompatActivity {
EditText editTextQuote;
EditText editTextAuthor;
Button btnSave;
ArrayList<Quote> arrQuo = new ArrayList<>();
public static ArrayList<Quote> arrayListQuotesSave;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_save_quote);
init();
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String quote = editTextQuote.getText().toString();
String author =editTextAuthor.getText().toString();
addQuote(quote,author);
}
});
}
private void init(){
editTextQuote = findViewById(R.id.editTextQuote);
editTextAuthor = findViewById(R.id.editTextAuthor);
btnSave = findViewById(R.id.buttonSave);
arrayListQuotesSave = new ArrayList<>();
}
private void addQuote(String quote, String author){
Quote q = new Quote(quote, author);
arrQuo.add(q);
String path = this.getFilesDir().toString();
try {
FileOutputStream fos = openFileOutput("Quotes.txt",MODE_APPEND);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(arrQuo);// when I write size = 1
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fis = openFileInput("Quotes.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
arrQuo =(ArrayList<Quote>) ois.readObject();
ois.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
I tried to passe a context and call the method openFileOutput on the context
so like this:
enter code here
FileOutputStream fs = context.openFileOutput("Quotes.txt", Context.MODE_PRIVATE);
enter code here
public class SaveQuote extends AppCompatActivity {
EditText editTextQuote;
EditText editTextAuthor;
Button btnSave;
ArrayList<Quote> arrQuo = new ArrayList<>();
public static ArrayList<Quote> arrayListQuotesSave;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_save_quote);
init();
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String quote = editTextQuote.getText().toString();
String author =editTextAuthor.getText().toString();
if(quote.isEmpty() || author.isEmpty()){
Toast.makeText(SaveQuote.this,"Fill all fields",Toast.LENGTH_SHORT).show();
}else {
writeToFile(SaveQuote.this, quote, author);
Toast.makeText(SaveQuote.this,"The quote was saved",Toast.LENGTH_SHORT).show();
}
}
});
}
private void init(){
editTextQuote = findViewById(R.id.editTextQuote);
editTextAuthor = findViewById(R.id.editTextAuthor);
btnSave = findViewById(R.id.buttonSave);
arrayListQuotesSave = new ArrayList<>();
}
private void writeToFile(Context context,String quote,String author) {
Quote q = new Quote(quote,author);
MainActivity.arrayListQuotesMain.add(q);
Integer size = MainActivity.arrayListQuotesMain.size();
Log.v("Added","arrayListQuotesMain size is = "+size.toString());
try {
FileOutputStream fs = context.openFileOutput("Quotes.txt", Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fs);
oos.writeObject(MainActivity.arrayListQuotesMain);
oos.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
editTextQuote.setText("");
editTextAuthor.setText("");
}
}

How to return a specific method on button click event?

Two buttons should update the value "PACK_LIB" inside "Stickers.java".
When they overwrite the String, the method setDefaultStickerPack() should be restarted.
When clicking on buttons b1 or b2 the value "PACK_LIB" will be overwritten by the value "allstickers" or "teststickers".
How can the button b1 or b2 restart the method "if(in==null) "inside setDefaultStickerPack() ?
-------KeyboardService.java
final Button button2 = (Button) mainBoard.findViewById(R.id.b2);
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Stickers.PACK_LIB = "allstickers";
stickers.setDefaultStickerPack();
showStickers();
}
});
final Button button3 = (Button) mainBoard.findViewById(R.id.b3);
button3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Stickers.PACK_LIB = "teststickers";
stickers.setDefaultStickerPack();
showStickers();
}
});
-------Stickers.java
public static String PACK_LIB ="";
public void setDefaultStickerPack() {
checkVersion(true);
InputStream in = null;
String packList[]=new String[0];
String PACK_APP="pack_app";
String PACK_ICON="pack_on.png";
String curAssets="";
try {
in = lContext.getAssets().open(PACK_APP+"/"+PACK_ICON);
curAssets=PACK_APP;
packList = lContext.getAssets().list(curAssets);
} catch (IOException e) {
e.printStackTrace();
}
if(in==null) {
try {
in = lContext.getAssets().open(PACK_LIB+"/"+PACK_ICON);
curAssets=PACK_LIB;
packList = lContext.getAssets().list(curAssets);
} catch (IOException e) {
e.printStackTrace();
}
}
if (in != null) {
long packId = 1;
PackData packData = new PackData();
packData.objectId = packId;
packData.name = "ROKOmoji";
packData.iconOn = copyImgFile(in, "i" + packId + "_on");
//packData.iconOff = copyImgFile(inOff, "i" + packId + "_off");
List<StickerData> stickerData = new ArrayList<StickerData>();
long i = 0;
for (String img: packList) {
if(PACK_ICON.equals(img)){
continue;
}
InputStream sIs = null;
try {
sIs = lContext.getAssets().open(curAssets+"/"+img);
} catch (IOException e) {
e.printStackTrace();
}
if (sIs != null) {
StickerData sd = new StickerData();
i=i+1;
File file = copyImgFile(sIs, "s" + img);
sd.objectId = i;
sd.imageId = i;
sd.packId = packId;
sd.packName = packData.name;
sd.file = file;
sd.iconKey = createIconKey(file, "si" + img);
sd.mime = getMimeTypeOfFile(file.getPath());//"image/gif"
sd.url = null;
stickerData.add(sd);
}
}
packData.stickers = stickerData;
packDataListDefault.add(packData);
}
}
U can call the method with parameter. try with this.
-------KeyboardService.java
final Button button2 = (Button) mainBoard.findViewById(R.id.b2);
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
stickers.setDefaultStickerPack("allstickers");
showStickers();
}
});
final Button button3 = (Button) mainBoard.findViewById(R.id.b3);
button3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
stickers.setDefaultStickerPack("teststickers");
showStickers();
}
});
-------Stickers.java
private static String PACK_LIB ="";
public void setDefaultStickerPack(String packLibValue) {
checkVersion(true);
InputStream in = null;
String packList[]=new String[0];
String PACK_APP="pack_app";
String PACK_ICON="pack_on.png";
String curAssets="";
PACK_LIB = packLibValue
try {
in = lContext.getAssets().open(PACK_APP+"/"+PACK_ICON);
curAssets=PACK_APP;
packList = lContext.getAssets().list(curAssets);
} catch (IOException e) {
e.printStackTrace();
}
if(in==null) {
try {
in = lContext.getAssets().open(PACK_LIB+"/"+PACK_ICON);
curAssets=PACK_LIB;
packList = lContext.getAssets().list(curAssets);
} catch (IOException e) {
e.printStackTrace();
}
}
..........
..........
}

Open file in TextView from txt file created in separate activity

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);
}
}

How to get text from EditText into integer variable

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.

Reading from a text file in android

I'm trying to read a random line from a file. My code doesn't have error, just comes up with a force close as soon as it runs in the emulator and I can't work out why!
public class filereader extends Activity {
TextView t = (TextView)findViewById(R.id.text);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
Scanner s = new Scanner(getResources().openRawResource(R.raw.lev1)); {
try {
while (s.hasNext()) {
String word = s.next();
t.setText(word);
}
}
finally {
s.close();
}
}
}
TextView t = (TextView)findViewById(R.id.text);
you can not run findViewById until the setContentView has been called:
TextView t = null; #Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
t = (TextView)findViewById(R.id.text);
}
please be sure that you declare text inside the main.xml
do this
BufferedReader myReader = null;
try
{
fIn = openFileInput("customer_number.txt");
myReader = new BufferedReader(new InputStreamReader(fIn));
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
String aDataRow = "";
//String aBuffer = "";
try
{
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
// TO display Whole Data of File
Toast.makeText(getBaseContext(),aBuffer,Toast.LENGTH_SHORT).show();
}
// To display Last Entered Number
Toast.makeText(getBaseContext(),last_number,Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public void readfromfile(){
try {
FileInputStream fileIn=openFileInput("mytextfile.txt");
InputStreamReader InputRead= new InputStreamReader(fileIn);
char[] inputBuffer= new char[READ_BLOCK_SIZE];
int charRead;
while ((charRead=InputRead.read(inputBuffer))>0) {
// char to string conversion
String readstring=String.copyValueOf(inputBuffer,0,charRead);
String s +=readstring;
}
InputRead.close();
Toast.makeText(getBaseContext(), s,Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
It will read the text file named "mytext.txt" string by string and store it by appending it to string variable s. So the variable "s" contains final string taken from file.

Categories

Resources