Reputation: 857
I am playing around with Android (extremely unfamiliar with it), and I am having trouble understanding what went wrong here -
Data declarations in class-
//data
DateFormat dateFormat = null;
Date date = null;
String _date = null;
Random random;
Code inside function onCreate-
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//get date and format it, then save it to a string
dateFormat = new SimpleDateFormat("yyyy/MM/dd");
date = new Date();
//set the textview object as string object in R file
TextView text = (TextView) findViewById(R.string.quote);
//if the date has changed, change the quote randomly
random = new Random();
//
text.setText(_date.equals(dateFormat.format(date))?(CharSequence)quotes[(random.nextInt(quotes.length)+1)]:(CharSequence)findViewById(R.string.quote));
//set date as new date
_date = dateFormat.format(date);
I know that's a really long and annoying ternary operation, and I feel that it may be why when I try to open the app in the emulator it stops working.
_date.equals(dateFormat.format(date)) ? (CharSequence) quotes[(random.nextInt(quotes.length) + 1)] :(CharSequence) findViewById(R.string.quote)
Any ideas as to what's going wrong?
Upvotes: 0
Views: 75
Reputation: 2423
You just don't have _date
initialized!
Just exchange the last two lines of code.
Edit
i just caught the logic of your code. Sorry, the problem is that onCreate
is called the first time your app is initiated. You must keep the date in a shared preference storage to remember its value from one time to the other:
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//get date and format it, then save it to a string
dateFormat = new SimpleDateFormat("yyyy/MM/dd");
date = dateformat.format(new Date());
//set the textview object as string object in R file
TextView text = (TextView) findViewById(R.id.quote);
//if the date has changed, change the quote randomly
random = new Random();
SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
String lastdatekey = "com.example.app.lastdate";
String _date = prefs.getString(lastdatekey, "");
String lastquotekey = "com.example.app.lastquote";
String lastquote = prefs.getString(lastquotekey, "");
if (!_date.equals(date)) {
String quote = quotes[(random.nextInt(quotes.length)+1)];
text.setText(quote);
//set date as new date
prefs.edit().putString(lastdaykey, date).putString(lastquotekey, quote).commit();
}
else {
text.setText(lastquote);
}
I think this will do it! Note how to store and retrieve information from one execution to the next with the private storage.
Upvotes: 2
Reputation: 513
This seems to be the problem
TextView text = (TextView) findViewById(R.string.quote);
You are trying to initialize a textview so it should be
TextView text = (TextView) findViewById(R.id.quote);
where R.id.quote is the id of your textview in the xml
Upvotes: 0