更新的数据库项不会显示在列表视图中

时间:2016-04-21 15:24:13

标签: android sqlite listview

在我的项目中,有一项活动是在数据库中添加一些信息。当我单击活动中的“添加”按钮时,它应该返回到主活动,其中有一个列表视图,该列表视图以列表形式显示数据库中的任务名称。直到,我在数据库表中只有Task Name字段,一切正常。但现在,我在表中添加了更多字段,如任务描述,任务日期等,列表视图不会使用新任务进行更新。这是代码:

/ **********主要活动************ /

package com.apps.katz.doer;

import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v7.app.AlertDialog;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.List;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    private ListView taskListView;
    private DataModel data;
    private DatabaseHandler db = new DatabaseHandler(this);
    private SimpleCursorAdapter adapter;
    private Cursor cursor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        refreshListView();

    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        int currentPosition;
        super.onCreateContextMenu(menu, v, menuInfo);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.context_menu, menu);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        switch (item.getItemId()) {
            case R.id.edit:
                Toast.makeText(this,"You chose Edit",Toast.LENGTH_LONG).show();
                return true;
            case R.id.delete:
                Toast.makeText(this,"Task Deleted",Toast.LENGTH_LONG).show();
                db.deleteTask((int)info.id);
                refreshListView();
                return true;
            default:
                return super.onContextItemSelected(item);
        }
    }

    private void refreshListView() {

        taskListView = (ListView) findViewById(R.id.task_list_view);
        cursor = db.queueAllTasks();
        String[] from = new String[] {"taskName"};
        int[] to = new int[] {R.id.text};
        adapter = new SimpleCursorAdapter(this, R.layout.row_item, cursor, from, to);
        taskListView.setAdapter(adapter);

        registerForContextMenu(taskListView);

    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        if (id == R.id.action_add_new_task) {
            startActivity(new Intent(MainActivity.this, AddTask.class));
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            // Handle the camera action
        } else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}

/ ************添加任务类************** /

package com.apps.katz.doer;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;

import java.util.Calendar;

public class AddTask extends AppCompatActivity {

    EditText input_task_title, input_task_desc, txtDate, txtTime;
    int mYear, mMonth, mDay, mHour, mMinute;
    Button btn_add_task;
    CheckBox checkBox;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_task);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        final DatabaseHandler db = new DatabaseHandler(this);

        input_task_title = (EditText) findViewById(R.id.input_task_title);
        input_task_desc = (EditText) findViewById(R.id.input_task_desc);
        txtDate = (EditText) findViewById(R.id.dateView);
        txtTime = (EditText) findViewById(R.id.timeView);

        checkBox = (CheckBox) findViewById(R.id.checkbox_add_reminder);
        checkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(((CheckBox)view).isChecked()) {
                    txtDate.setVisibility(View.VISIBLE);
                    txtTime.setVisibility(View.VISIBLE);
                } else if (((CheckBox)view).isChecked() == false) {
                    txtDate.setVisibility(View.GONE);
                    txtTime.setVisibility(View.GONE);
                }
            }
        });

        txtDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final Calendar calendar = Calendar.getInstance();
                mYear = calendar.get(Calendar.YEAR);
                mMonth = calendar.get(Calendar.MONTH);
                mYear = calendar.get(Calendar.YEAR);
                DatePickerDialog dateDialog = new DatePickerDialog(AddTask.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
                        txtDate.setText(i2+"/"+(i1+1)+"/"+i);
                    }
                },mYear,mMonth,mDay);
                dateDialog.show();
            }
        });

        txtTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final Calendar calendar = Calendar.getInstance();
                mHour = calendar.get(Calendar.HOUR_OF_DAY);
                mMinute = calendar.get(Calendar.MINUTE);
                TimePickerDialog timeDialog = new TimePickerDialog(AddTask.this, new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker timePicker, int i, int i1) {
                        txtTime.setText(i+":"+i1);
                    }
                },mHour,mMinute,false);
                timeDialog.show();
            }
        });


        btn_add_task = (Button) findViewById(R.id.btn_add_task);
        btn_add_task.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                db.addTask(new DataModel(input_task_title.getText().toString(),input_task_desc.getText().toString(),
                        checkBox.isChecked(),txtDate.getText().toString(),txtTime.getText().toString()));
                Toast.makeText(getApplicationContext(),R.string.new_task_added,Toast.LENGTH_LONG).show();
                startActivity(new Intent(AddTask.this,MainActivity.class));
            }
        });
    }

}

/ **************** DBHandler班级***************** /

package com.apps.katz.doer;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by katz on 15/4/16.
 */
public class DatabaseHandler extends SQLiteOpenHelper{

    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME="com.app.katz.doer";
    private static final String TABLE_NAME="tasks";
    private static final String KEY_ID="id";
    private static final String KEY_COL_TASK_NAME="taskName";
    private static final String KEY_COL_TASK_DESC="taskDesc";
    private static final String KEY_COL_IS_REMINDER="isReminder";
    private static final String KEY_COL_DATE="taskDate";
    private static final String KEY_COL_TIME="taskTime";

    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {

        String CREATE_TASKS_TABLE = "create table "+TABLE_NAME+"("+KEY_ID+" integer primary key autoincrement, " +
                ""+KEY_COL_TASK_NAME+" text, " +
                ""+KEY_COL_TASK_DESC+" text, " +
                ""+KEY_COL_IS_REMINDER+" boolean, " +
                ""+KEY_COL_DATE+" text, " +
                ""+KEY_COL_TIME+" text)";
        sqLiteDatabase.execSQL(CREATE_TASKS_TABLE);

    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

        sqLiteDatabase.execSQL("drop table if exists "+TABLE_NAME);
        onCreate(sqLiteDatabase);

    }

    public void addTask(DataModel data) {

        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(KEY_COL_TASK_NAME,data.getTaskTitle());
        values.put(KEY_COL_TASK_DESC,data.getTaskDesc());
        values.put(KEY_COL_IS_REMINDER,data.getReminder());
        values.put(KEY_COL_DATE,data.getTaskDate());
        values.put(KEY_COL_TIME,data.getTaskTime());
        db.insert(TABLE_NAME,null,values);
        db.close();
    }

    public Cursor queueAllTasks() {

        String[] columns = new String[]{KEY_ID,KEY_COL_TASK_NAME};
        Cursor cursor = getReadableDatabase().rawQuery("select id as _id, taskName from tasks", null);
        return cursor;
    }

    public void deleteTask(int id) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_NAME, KEY_ID + " =?",
                new String[] {String.valueOf(id)});
        db.close();
    }
}

/ ***************数据模型类************** /

package com.apps.katz.doer;

/**
 * Created by katz on 14/4/16.
 */
public class DataModel {

    int id;
    private String taskTitle;
    private String taskDesc;
    private Boolean isReminder;
    private String taskDate;
    private String taskTime;

    public DataModel(){

    }

    public DataModel(int id) {
        this.id=id;
    }

    public DataModel(int id, String taskTitle, String taskDesc, Boolean isReminder,String taskDate, String taskTime){
        this.id=id;
        this.taskTitle=taskTitle;
        this.taskDesc=taskDesc;
        this.isReminder=isReminder;
        this.taskDate=taskDate;
        this.taskTime=taskTime;
    }

    public DataModel(String taskTitle, String taskDesc, Boolean isReminder, String taskDate, String taskTime) {
        this.taskTitle = taskTitle;
        this.taskDesc = taskDesc;
        this.isReminder = isReminder;
        this.taskDate = taskDate;
        this.taskTime = taskTime;
    }

    public DataModel(int id, String taskTitle, String taskDesc) {
        this.taskTitle = taskTitle;
        this.taskDesc = taskDesc;
        this.id=id;
    }

    public DataModel(String taskTitle, String taskDesc) {
        this.taskTitle = taskTitle;
        this.taskDesc = taskDesc;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTaskTitle() {
        return taskTitle;
    }

    public void setTaskTitle(String taskTitle) {
        this.taskTitle = taskTitle;
    }

    public String getTaskDesc() {
        return taskDesc;
    }

    public void setTaskDesc(String taskDesc) {
        this.taskDesc = taskDesc;
    }

    public Boolean getReminder() {
        return isReminder;
    }

    public void setReminder(Boolean reminder) {
        isReminder = reminder;
    }

    public String getTaskDate() {
        return taskDate;
    }

    public void setTaskDate(String taskDate) {
        this.taskDate = taskDate;
    }

    public String getTaskTime() {
        return taskTime;
    }

    public void setTaskTime(String taskTime) {
        this.taskTime = taskTime;
    }
}

请在我出错的地方帮忙!

提前致谢。

这是日志错误

table tasks has no column named taskDesc
04-22 19:14:36.151 2897-2897/com.apps.katz.doer E/SQLiteDatabase: Error inserting taskDesc=TaskTask TaskerTasked taskTime=19:14 taskName=TaskTask taskDate=31/3/2016 isReminder=true
                                                                  android.database.sqlite.SQLiteException: table tasks has no column named taskDesc (code 1): , while compiling: INSERT INTO tasks(taskDesc,taskTime,taskName,taskDate,isReminder) VALUES (?,?,?,?,?)
                                                                      at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                                                                      at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
                                                                      at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498)
                                                                      at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                                                                      at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
                                                                      at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
                                                                      at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1469)
                                                                      at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
                                                                      at com.apps.katz.doer.DatabaseHandler.addTask(DatabaseHandler.java:61)
                                                                      at com.apps.katz.doer.AddTask$4.onClick(AddTask.java:98)
                                                                      at android.view.View.performClick(View.java:5198)
                                                                      at android.view.View$PerformClick.run(View.java:21147)
                                                                      at android.os.Handler.handleCallback(Handler.java:739)
                                                                      at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                      at android.os.Looper.loop(Looper.java:148)
                                                                      at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

1 个答案:

答案 0 :(得分:0)

通过从主机设备卸载应用程序,然后将数据库版本更改为2(除1以外的任何其他内容)解决了此问题。安装了应用程序,一切都像魅力一样。