Reputation: 1
So, i have a button which function is to update my TextView. Every time someone clicks the button to the current date. But, for some reason it only works once. I have tried both XML onClick method and Java setOnClickListener, not one works. Can someone please help me on solving this problem?
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import org.w3c.dom.Text;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends AppCompatActivity {
Date date = Calendar.getInstance().getTime();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void btnClick(View i){
String time = ((EditText) findViewById(R.id.editTextTime)).getText().toString();
String url = ((EditText) findViewById(R.id.editText)).getText().toString();
TextView txtErr = findViewById(R.id.errorLog);
txtErr.setText(date.toString());
}
}
Upvotes: 0
Views: 358
Reputation: 5980
You are initialising the date only once (when your MainActivity
is instantiated). Therefore each time you set the text, you're using the same date instance.
Instead you should be getting a new date each time the button is clicked, something like:
public void btnClick(View i){
String time = ((EditText) findViewById(R.id.editTextTime)).getText().toString();
String url = ((EditText) findViewById(R.id.editText)).getText().toString();
TextView txtErr = findViewById(R.id.errorLog);
Date date = Calendar.getInstance().getTime();
txtErr.setText(date.toString());
}
As a side note, I wouldn't recommend using the Calendar
APIs anymore. Instead take a look at the new, more modern, java.time
library which you can take a look at here.
Upvotes: 3