时间/日期选择器无法识别字符串

发布于 2024-09-06 12:18:02 字数 8208 浏览 3 评论 0原文

这是我正在使用的代码片段。我正在为 Android 制作一个应用程序,一切都很顺利,除了这个问题,谷歌在这方面并不是我的朋友。我已经强调了重要的部分。问题是,当使用 updateboxes() 方法向 TextView 加载数据时,一切正常。当它们使用 populateFields() 加载时;方法时间或日期选择器无法识别这些值,因为它们直接来自数据库,而不是像 updateboxes() 方法那样使用 stringBuilder 构建。

字符串不是我的强项,我唯一能想到的就是将字符串分解回单独的 mDay mMonth mYear 值,然后通过 updateBoxes() 方法运行它们,但我认为会有一种更简单的方法。无论如何我都不知道该怎么做。

这是代码:

package com.example.TimeClockAppreset;


import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.AdapterView.OnItemSelectedListener;

public class TimesEdit extends Activity{

    private TimesDbAdapter mDbHelper;
    private Long mRowId;

    private TextView mDateBox;
    private TextView mTimeBox;

    private int mYear;
    private int mMonth;
    private int mDay;
    private int mHour;
    private int mMinute;

    static final int TIME_DIALOG_ID = 0;
    static final int DATE_DIALOG_ID = 1;


         protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            mDbHelper = new TimesDbAdapter(this);
            mDbHelper.open();

            setContentView(R.layout.entry_edit);

            mDateBox = (TextView) findViewById(R.id.DateBox);
            mTimeBox = (TextView) findViewById(R.id.TimeBox);

            Button changeTime = (Button) findViewById(R.id.changeTime);
            Button changeDate = (Button) findViewById(R.id.changeDate);
            Button confirmButton = (Button) findViewById(R.id.confirm);

            Spinner spinner = (Spinner) findViewById(R.id.spinner);
            ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                    this, R.array.ClockBox_array, android.R.layout.simple_spinner_item);
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinner.setAdapter(adapter);

            spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());

            mRowId = (savedInstanceState == null) ? null :
                (Long) savedInstanceState.getSerializable(TimesDbAdapter.KEY_ROWID);
            if (mRowId == null) {
                Bundle extras = getIntent().getExtras();
                mRowId = extras != null ? extras.getLong(TimesDbAdapter.KEY_ROWID)
                                        : null;
            }

            //updateBoxes();
            populateFields();

            changeTime.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    showDialog(TIME_DIALOG_ID);
                }
            });

            changeDate.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    showDialog(DATE_DIALOG_ID);
                }
            });

            confirmButton.setOnClickListener(new View.OnClickListener() {

                public void onClick(View view) {
                    setResult(RESULT_OK);

                    finish();
                }

            });
     }

         //THIS GETS THE INFO AND POPULATES THE FIELDS
         private void populateFields() {
                if (mRowId != null) {
                    Cursor time = mDbHelper.fetchTime(mRowId);
                    startManagingCursor(time);
                    mDateBox.setText(time.getString(
                                time.getColumnIndexOrThrow(TimesDbAdapter.KEY_DATE)));
                    mTimeBox.setText(time.getString(
                            time.getColumnIndexOrThrow(TimesDbAdapter.KEY_TIME)));
                }
                else
                    updateBoxes();
            }

             private void updateBoxes() {
                final Calendar c = Calendar.getInstance();
                mYear = c.get(Calendar.YEAR);
                mMonth = c.get(Calendar.MONTH);
                mDay = c.get(Calendar.DAY_OF_MONTH);
                mHour = c.get(Calendar.HOUR_OF_DAY);
                mMinute = c.get(Calendar.MINUTE);
                updateDateDisplay();
                updateTimeDisplay();
         }

         private void updateDateDisplay() {
                mDateBox.setText(
                        new StringBuilder()
                                // Month is 0 based so add 1
                                .append(mMonth + 1).append("-")
                                .append(mDay).append("-")
                                .append(mYear).append(" "));
    }

         private void updateTimeDisplay() {
            mTimeBox.setText(
                    new StringBuilder()
                    .append(pad(mHour)).append(":")
                    .append(pad(mMinute)));
        }

         private static String pad(int c) {
                if (c >= 10)
                    return String.valueOf(c);
                else
                    return "0" + String.valueOf(c);
            }

         public class MyOnItemSelectedListener implements OnItemSelectedListener {

                public void onItemSelected(AdapterView<?> parent,
                    View view, int pos, long id) {
                }

                @SuppressWarnings("unchecked")
                public void onNothingSelected(AdapterView parent) {
                  // Do nothing.
                }
            }

         private TimePickerDialog.OnTimeSetListener mTimeSetListener =
                new TimePickerDialog.OnTimeSetListener() {
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        mHour = hourOfDay;
                        mMinute = minute;
                        updateTimeDisplay();
                    }
                };

         private DatePickerDialog.OnDateSetListener mDateSetListener =
                    new DatePickerDialog.OnDateSetListener() {

                        public void onDateSet(DatePicker view, int year,
                                              int monthOfYear, int dayOfMonth) {
                            mYear = year;
                            mMonth = monthOfYear;
                            mDay = dayOfMonth;
                            updateDateDisplay();
                        }
                    };

         @Override
         protected Dialog onCreateDialog(int id) {
                        switch (id) {
                        case DATE_DIALOG_ID:
                            return new DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay);
                        case TIME_DIALOG_ID:
                            return new TimePickerDialog(this, mTimeSetListener, mHour, mMinute, false);
                        }
                        return null;
                    }

         private void saveState() {
                String date = mDateBox.getText().toString();
                String time = mTimeBox.getText().toString();
                String inOut = "NA";
                if (mRowId == null) {
                    long id = mDbHelper.createEntry(time, date, inOut);
                    if (id > 0) {
                        mRowId = id;
                    }
                } else {
                    mDbHelper.updateTimeTest(mRowId, time, date);
                }
            }

         @Override
            protected void onSaveInstanceState(Bundle outState) {
                super.onSaveInstanceState(outState);
                saveState();
                outState.putSerializable(TimesDbAdapter.KEY_ROWID, mRowId);
            }

         @Override
         protected void onPause() {
                super.onPause();
                saveState();
            }

         @Override
         protected void onResume() {
                super.onResume();
                populateFields();
            }

}

任何帮助将不胜感激。考虑到其他一切都很好,这个问题让我发疯。

Here is a snippet of code that i am working with. I am making an app for android and everything is going great except this one problem and google has not been my friend on this. I have highlighted the important parts. The problem is when the TextViews are loaded with data using the updateboxes() method everything works great. When they are loaded with the populateFields(); method the time or date picker doesnt recognize the values since they come straight from the database and not built with stringBuilder like the updateboxes() method.

Strings are not my strong point and the only thing that i can think of doing is breaking the strings back down into individual mDay mMonth mYear values and then run them back through the updateBoxes() method but i would think there would be an easier way. I wouldnt know how to do that anyway.

Here is the code:

package com.example.TimeClockAppreset;


import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.AdapterView.OnItemSelectedListener;

public class TimesEdit extends Activity{

    private TimesDbAdapter mDbHelper;
    private Long mRowId;

    private TextView mDateBox;
    private TextView mTimeBox;

    private int mYear;
    private int mMonth;
    private int mDay;
    private int mHour;
    private int mMinute;

    static final int TIME_DIALOG_ID = 0;
    static final int DATE_DIALOG_ID = 1;


         protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            mDbHelper = new TimesDbAdapter(this);
            mDbHelper.open();

            setContentView(R.layout.entry_edit);

            mDateBox = (TextView) findViewById(R.id.DateBox);
            mTimeBox = (TextView) findViewById(R.id.TimeBox);

            Button changeTime = (Button) findViewById(R.id.changeTime);
            Button changeDate = (Button) findViewById(R.id.changeDate);
            Button confirmButton = (Button) findViewById(R.id.confirm);

            Spinner spinner = (Spinner) findViewById(R.id.spinner);
            ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                    this, R.array.ClockBox_array, android.R.layout.simple_spinner_item);
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinner.setAdapter(adapter);

            spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());

            mRowId = (savedInstanceState == null) ? null :
                (Long) savedInstanceState.getSerializable(TimesDbAdapter.KEY_ROWID);
            if (mRowId == null) {
                Bundle extras = getIntent().getExtras();
                mRowId = extras != null ? extras.getLong(TimesDbAdapter.KEY_ROWID)
                                        : null;
            }

            //updateBoxes();
            populateFields();

            changeTime.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    showDialog(TIME_DIALOG_ID);
                }
            });

            changeDate.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    showDialog(DATE_DIALOG_ID);
                }
            });

            confirmButton.setOnClickListener(new View.OnClickListener() {

                public void onClick(View view) {
                    setResult(RESULT_OK);

                    finish();
                }

            });
     }

         //THIS GETS THE INFO AND POPULATES THE FIELDS
         private void populateFields() {
                if (mRowId != null) {
                    Cursor time = mDbHelper.fetchTime(mRowId);
                    startManagingCursor(time);
                    mDateBox.setText(time.getString(
                                time.getColumnIndexOrThrow(TimesDbAdapter.KEY_DATE)));
                    mTimeBox.setText(time.getString(
                            time.getColumnIndexOrThrow(TimesDbAdapter.KEY_TIME)));
                }
                else
                    updateBoxes();
            }

             private void updateBoxes() {
                final Calendar c = Calendar.getInstance();
                mYear = c.get(Calendar.YEAR);
                mMonth = c.get(Calendar.MONTH);
                mDay = c.get(Calendar.DAY_OF_MONTH);
                mHour = c.get(Calendar.HOUR_OF_DAY);
                mMinute = c.get(Calendar.MINUTE);
                updateDateDisplay();
                updateTimeDisplay();
         }

         private void updateDateDisplay() {
                mDateBox.setText(
                        new StringBuilder()
                                // Month is 0 based so add 1
                                .append(mMonth + 1).append("-")
                                .append(mDay).append("-")
                                .append(mYear).append(" "));
    }

         private void updateTimeDisplay() {
            mTimeBox.setText(
                    new StringBuilder()
                    .append(pad(mHour)).append(":")
                    .append(pad(mMinute)));
        }

         private static String pad(int c) {
                if (c >= 10)
                    return String.valueOf(c);
                else
                    return "0" + String.valueOf(c);
            }

         public class MyOnItemSelectedListener implements OnItemSelectedListener {

                public void onItemSelected(AdapterView<?> parent,
                    View view, int pos, long id) {
                }

                @SuppressWarnings("unchecked")
                public void onNothingSelected(AdapterView parent) {
                  // Do nothing.
                }
            }

         private TimePickerDialog.OnTimeSetListener mTimeSetListener =
                new TimePickerDialog.OnTimeSetListener() {
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        mHour = hourOfDay;
                        mMinute = minute;
                        updateTimeDisplay();
                    }
                };

         private DatePickerDialog.OnDateSetListener mDateSetListener =
                    new DatePickerDialog.OnDateSetListener() {

                        public void onDateSet(DatePicker view, int year,
                                              int monthOfYear, int dayOfMonth) {
                            mYear = year;
                            mMonth = monthOfYear;
                            mDay = dayOfMonth;
                            updateDateDisplay();
                        }
                    };

         @Override
         protected Dialog onCreateDialog(int id) {
                        switch (id) {
                        case DATE_DIALOG_ID:
                            return new DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay);
                        case TIME_DIALOG_ID:
                            return new TimePickerDialog(this, mTimeSetListener, mHour, mMinute, false);
                        }
                        return null;
                    }

         private void saveState() {
                String date = mDateBox.getText().toString();
                String time = mTimeBox.getText().toString();
                String inOut = "NA";
                if (mRowId == null) {
                    long id = mDbHelper.createEntry(time, date, inOut);
                    if (id > 0) {
                        mRowId = id;
                    }
                } else {
                    mDbHelper.updateTimeTest(mRowId, time, date);
                }
            }

         @Override
            protected void onSaveInstanceState(Bundle outState) {
                super.onSaveInstanceState(outState);
                saveState();
                outState.putSerializable(TimesDbAdapter.KEY_ROWID, mRowId);
            }

         @Override
         protected void onPause() {
                super.onPause();
                saveState();
            }

         @Override
         protected void onResume() {
                super.onResume();
                populateFields();
            }

}

Any help would be appreciated. This problem is driving me crazy considering everything else is good to go.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

他是夢罘是命 2024-09-13 12:18:02

好吧,长话短说,据我所知,除非您使用当前月份,否则 getMonth() 方法不起作用。奇怪的是, getYear() 和 getDate() 方法都可以工作,但它们重写了 getMonth() 方法,其原因超出了我的理解。

这是简单的解决方案。

公共类 GetDateValues {
私有字符串日期;
私人字符短划线;

public GetDateValues(String str, char sep) {
    date = str;
    dash = sep;
}

public String month() {
    int dot = date.indexOf(dash);
    return date.substring(0,dot);
}

public String day() {
    int dot = date.lastIndexOf(dash);
    int sep = date.indexOf(dash);
    return date.substring(sep + 1, dot);
}

public String year() {
    int sep = date.lastIndexOf(dash);
    return date.substring(sep + 1, sep + 5);
}

现在

您有了为 varius 选择器重新制作字符串的值。

Ok well to make a long story short, as far as i can tell the getMonth() method does not work unless you are working with the current month. Its strange the getYear() and getDate() methods both work but they have rewritten the getMonth() method for reasons beyond my understanding.

Here is the simple solution.

public class GetDateValues {
private String date;
private char dash;

public GetDateValues(String str, char sep) {
    date = str;
    dash = sep;
}

public String month() {
    int dot = date.indexOf(dash);
    return date.substring(0,dot);
}

public String day() {
    int dot = date.lastIndexOf(dash);
    int sep = date.indexOf(dash);
    return date.substring(sep + 1, dot);
}

public String year() {
    int sep = date.lastIndexOf(dash);
    return date.substring(sep + 1, sep + 5);
}

}

Now you have the values to remake the strings for the varius pickers.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文