Sqlite数据库日期显示在ListView中

时间:2014-09-27 09:29:49

标签: android sqlite listview

MainActivity类。

公共类MainActivity扩展了Activity {

EditText etName, etEmail, etPhone, etDesignation;
DatabaseHelper dbHelper;

// declare view
ListView lvEmployees;
// declare adapter
CustomizedAdapter adapter;
Employee employee;

// datasource

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    etName = (EditText) findViewById(R.id.etName);
    lvEmployees = (ListView) findViewById(R.id.lvEmployees);
    dbHelper = new DatabaseHelper(this);
    Employee employee;
}

public void save(View v) {
    String name = etName.getText().toString();
    SimpleDateFormat sm = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
    Date today = Calendar.getInstance().getTime();
    String reportDate = sm.format(today);

    Employee employee = new Employee(name, reportDate);
    Toast.makeText(getApplicationContext(), employee.toString(),
            Toast.LENGTH_LONG).show();

    long inserted = dbHelper.insertEmployee(employee);
    if (inserted >= 0) {
        Toast.makeText(getApplicationContext(), "Data inserted",
                Toast.LENGTH_LONG).show();
    } else {
        Toast.makeText(getApplicationContext(), "Data insertion failed...",
                Toast.LENGTH_LONG).show();
    }

}

public void view(View v) {
    ArrayList<Employee> employees = dbHelper.getAllEmployees();
    if (employees != null && employees.size() > 0) {
        adapter = new CustomizedAdapter(this, employees);
        lvEmployees.setAdapter(adapter);
    }

}

}

这是我的DataBasehelper

公共类DatabaseHelper扩展了SQLiteOpenHelper {

public static final String DB_NAME = "task_management";
public static final int DB_VERSION = 1;

public static final String EMPLOYEE_TABLE = "employee";
public static final String ID_FIELD = "_id";
public static final String NAME_FIELD = "name";
public static final String TIME_DATE = "time_date";

public static final String EMPLOYEE_TABLE_SQL = "CREATE TABLE "
        + EMPLOYEE_TABLE + " (" + ID_FIELD + " INTEGER PRIMARY KEY, "
        + NAME_FIELD + " TEXT, " + TIME_DATE + " DATETIME);";

public DatabaseHelper(Context context) {
    super(context, DB_NAME, null, DB_VERSION);

}

@Override
public void onCreate(SQLiteDatabase db) {
    // create tables
    db.execSQL(EMPLOYEE_TABLE_SQL);
    Log.e("TABLE CREATE", EMPLOYEE_TABLE_SQL);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // upgrade logic

}

// insert
public long insertEmployee(Employee emp) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();

    values.put(NAME_FIELD, emp.getName());
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
    String date = sdf.format(emp.getDate());
    values.put(TIME_DATE, date);
    long inserted = db.insert(EMPLOYEE_TABLE, null, values);

    db.close();
    return inserted;
}

// query
public ArrayList<Employee> getAllEmployees() {
    ArrayList<Employee> allEmployees = new ArrayList<Employee>();
    SQLiteDatabase db = this.getReadableDatabase();

    // String[] columns={NAME_FIELD, EMAIL_FIELD, PHONE_FIELD};
    // SELECT * FROM EMPLOYEE;
    Cursor cursor = db.query(EMPLOYEE_TABLE, null, null, null, null, null,
            null);

    // Cursor cursor = db.rawQuery("SELECT * FROM EMPLOYEE", null);
    if (cursor != null && cursor.getCount() > 0) {
        cursor.moveToFirst();
        for (int i = 0; i < cursor.getCount(); i++) {
            //
            int id = cursor.getInt(cursor.getColumnIndex(ID_FIELD));
            String name = cursor.getString(cursor
                    .getColumnIndex(NAME_FIELD));
            String datetime = cursor.getString(cursor
                    .getColumnIndex(TIME_DATE));
            Employee e = new Employee(name, datetime);
            allEmployees.add(e);
            cursor.moveToNext();
        }
    }
    cursor.close();
    db.close();

    return allEmployees;
}

}

自定义适配器..

公共类CustomizedAdapter扩展了ArrayAdapter {

Activity con;
ArrayList<Employee> employeeList;
Employee employee;

public CustomizedAdapter(Context context, ArrayList<Employee> employees) {
    super(context, R.layout.list_item, employees);
    this.con = (Activity) context;
    this.employeeList = employees;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View v = null;
    if (convertView == null) {
        // generate a view and return
        LayoutInflater inflater = con.getLayoutInflater();
        v = inflater.inflate(R.layout.list_item, null);

        TextView txtName = (TextView) v.findViewById(R.id.txtName);
        TextView datee = (TextView) v.findViewById(R.id.txtEmail);
        Employee e = employeeList.get(position);
        Date date = e.getDate();
        // Date date = e.get(position).getWishDate();
        datee.setText(DateFormat.format("dd/MM/yyyy hh:mm:ss a", date));
        txtName.setText(e.getName());
        datee.setText(e.getDatetime());

    } else {
        v = convertView;
    }
    return v;
}

}

这是LogCat:

09-27 16:11:35.374: E/AndroidRuntime(32300): FATAL EXCEPTION: main

09-27 16:11:35.374: E/AndroidRuntime(32300): java.lang.IllegalStateException: Could not execute method of the activity

09-27 16:11:35.374: E/AndroidRuntime(32300):    at android.view.View$1.onClick(View.java:3609)

09-27 16:11:35.374: E/AndroidRuntime(32300):    at android.view.View.performClick(View.java:4102)

09-27 16:11:35.374: E/AndroidRuntime(32300):    at android.view.View$PerformClick.run(View.java:17085)

09-27 16:11:35.374: E/AndroidRuntime(32300):    at android.os.Handler.handleCallback(Handler.java:615)

09-27 16:11:35.374: E/AndroidRuntime(32300):    at android.os.Handler.dispatchMessage(Handler.java:92)

09-27 16:11:35.374: E/AndroidRuntime(32300):    at android.os.Looper.loop(Looper.java:155)
09-27 16:11:35.374: E/AndroidRuntime(32300):    at 
android.app.ActivityThread.main(ActivityThread.java:5511)

09-27 16:11:35.374: E/AndroidRuntime(32300):    at java.lang.reflect.Method.invokeNative(Native Method)

09-27 16:11:35.374: E/AndroidRuntime(32300):    at java.lang.reflect.Method.i
nvoke(Method.java:511)

09-27 16:11:35.374: E/AndroidRuntime(32300):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1029)

09-27 16:11:35.374: E/AndroidRuntime(32300):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:796)

09-27 16:11:35.374: E/AndroidRuntime(32300):    at dalvik.system.NativeStart.main(Native Method)

09-27 16:11:35.374: E/AndroidRuntime(32300): Caused by: java.lang.reflect.InvocationTargetException

09-27 16:11:35.374: E/AndroidRuntime(32300):    at java.lang.reflect.Method.invokeNative(Native Method)
09-27 16:11:35.374: E/AndroidRuntime(32300):    at java.lang.reflect.Method.invoke(Method.java:511)

09-27 16:11:35.374: E/AndroidRuntime(32300):    at android.view.View$1.onClick(View.java:3604)
09-27 16:11:35.374: E/AndroidRuntime(32300):    ... 11 more

09-27 16:11:35.374: E/AndroidRuntime(32300): Caused by: java.lang.NullPointerException

09-27 16:11:35.374: E/AndroidRuntime(32300):    at java.util.Calendar.setTime(Calendar.java:1324)

09-27 16:11:35.374: E/AndroidRuntime(32300):    at 
java.text.SimpleDateFormat.formatImpl(SimpleDateFormat.java:536)

09-27 16:11:35.374: E/AndroidRuntime(32300):    at java.text.SimpleDateFormat.format(SimpleDateFormat.java:821)

09-27 16:11:35.374: E/AndroidRuntime(32300):    at java.text.DateFormat.format(DateFormat.java:376)
09-27 16:11:35.374: E/AndroidRuntime(32300):    at

com.shikkhok.taskmanagement.DatabaseHelper.insertEmployee(DatabaseHelper.java:51)
09-27 16:11:35.374: E/AndroidRuntime(32300):    at 

com.shikkhok.taskmanagement.MainActivity.save(MainActivity.java:48)

09-27 16:11:35.374: E/AndroidRuntime(32300):    ... 14 more

09-27 16:11:35.394: E/EmbeddedLogger(426): App crashed! Process: com.shikkhok.taskmanagement

09-27 16:11:35.394: E/EmbeddedLogger(426): App crashed! Package: com.shikkhok.taskmanagement v1 (1.0)

09-27 16:11:35.394: E/EmbeddedLogger(426): Application Label: My Task Management

09-27 16:11:36.124: E/Trace(32345): error opening trace file: No such file or directory (2)

我想将当前时间和日期显示在ListView中,并希望将其保存到数据库中。 我想选择日期和时间,并希望将其保存为我的Sqlite数据库中的String。 当我想保存我的约会时,应用程序就会停止。 那怎么解决呢?

1 个答案:

答案 0 :(得分:0)

format()类中的方法SimpleDateFromat获取Date值并返回一个字符串。就像你在这里一样:

Date today = Calendar.getInstance().getTime();
String reportDate = sm.format(today);
Employee employee = new Employee(name, reportDate);

所以emp.getDate()返回一个字符串,当你说:

时,你正在重新格式化它
String date = sdf.format(emp.getDate());

实际上,您正在转换的字符串值不是Date值。

你有两种方法。如果您想真正将Date值添加到您的表格中(我不确定Sqlite支持此项),您应该使用此:

values.put(NAME_FIELD, emp.getName());
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
Date date = sdf.parse(emp.getDate());
values.put(TIME_DATE, date);
long inserted = db.insert(EMPLOYEE_TABLE, null, values);

另一种方法是将列类型从DATETIME更改为TEXT

public static final String EMPLOYEE_TABLE_SQL = "CREATE TABLE "
        + EMPLOYEE_TABLE + " (" + ID_FIELD + " INTEGER PRIMARY KEY, "
        + NAME_FIELD + " TEXT, " + TIME_DATE + " TEXT);";

完成此更改后,您可以轻松使用此功能:

values.put(NAME_FIELD, emp.getName());
values.put(TIME_DATE, emp.getDate());
long inserted = db.insert(EMPLOYEE_TABLE, null, values);

我希望这可以帮到你。