0

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?

4

2 回答 2

2

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.

于 2013-09-08T21:26:16.100 回答
0

这似乎是问题

TextView text = (TextView) findViewById(R.string.quote);

您正在尝试初始化一个 textview 所以它应该是

TextView text = (TextView) findViewById(R.id.quote);

其中 R.id.quote 是 xml 中 textview 的 id

于 2013-09-08T21:31:10.707 回答