2016-06-01 141 views
1

我正在创建一个简单的程序,它在表中存储文本和计数。这些数据显示在listView中。我在更新数据时遇到问题。但是,关闭并打开应用程序时,数据加载正常。我已经包含了我的程序。无法从数据库中获取数据

MainActivity:

public class MainActivity extends AppCompatActivity { 

    private List<Habit> habits; 
    private ListAdapter adapter; 
    private DatabaseHandler handler; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
     setSupportActionBar(toolbar); 
     handler = new DatabaseHandler(getApplicationContext()); 
     habits = handler.getAllHabit(); 
     View empty = getLayoutInflater().inflate(R.layout.list_item_empty, null, false); 
     addContentView(empty, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); 
     ListView habitList = (ListView) findViewById(R.id.habitList); 
     adapter = new ListAdapter(habits); 
     if (habitList != null) { 
      habitList.setAdapter(adapter); 
      habitList.setEmptyView(empty); 
      habitList.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
       @Override 
       public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
        Habit habit = (Habit) adapter.getItem(position); 
        habit.updateCount(); 
        handler.updateHabit(habit); 
        updateList(); 
       } 
      }); 
      habitList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { 
       @Override 
       public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { 
        Habit habit = (Habit) adapter.getItem(position); 
        handler.deleteHabit(habit); 
        updateList(); 
        return true; 
       } 
      }); 
     } 
    } 


    private void getNewHabit() { 

     final AlertDialog.Builder alertDialog = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.Dialog)); 
     alertDialog.setTitle("New Habit"); 
     alertDialog.setMessage("Enter the name of the new habit"); 
     final EditText input = new EditText(getApplicationContext()); 
     int padding = Math.round(getResources().getDimension(R.dimen.margin)); 
     input.setPadding(padding,padding,padding,padding); 
     LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); 
     input.setLayoutParams(params); 
     alertDialog.setView(input); 
     alertDialog.setPositiveButton("Add", new DialogInterface.OnClickListener() { 
      @Override 
      public void onClick(DialogInterface dialog, int which) { 
       Habit habit = new Habit(); 
       habit.setHabit(input.getText().toString()); 
       habit.setCount(0); 
       handler.addHabit(habit); 
       updateList(); 
      } 
     }); 
     alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
      @Override 
      public void onClick(DialogInterface dialog, int which) { 
       dialog.dismiss(); 
      } 
     }); 
     alertDialog.show(); 
    } 

    private void updateList() { 
     habits.clear(); 
     habits = handler.getAllHabit(); 
     adapter.notifyDataSetChanged(); 
    } 
} 

数据库处理器:

class DatabaseHandler extends SQLiteOpenHelper { 

    private static final int DATABASE_VERSION = 1; 
    private static final String DATABASE_NAME = "habitDatabase"; 
    private static final String TABLE_NAME = "userHabits"; 
    private static final String KEY_ID = "id"; 
    private static final String KEY_HABIT_NAME = "name"; 
    private static final String KEY_HABIT_COUNT = "count"; 

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

    @Override 
    public void onCreate(SQLiteDatabase db) { 
     String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + "(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_HABIT_NAME + " TEXT," + KEY_HABIT_COUNT + " INTEGER)"; 
     db.execSQL(CREATE_TABLE); 
    } 

    @Override 
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
     db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); 
     onCreate(db); 
    } 

    public void addHabit(Habit habit) { 
     SQLiteDatabase db = this.getWritableDatabase(); 
     ContentValues values = new ContentValues(); 
     values.put(KEY_HABIT_NAME, habit.getHabit()); 
     values.put(KEY_HABIT_COUNT, habit.getCount()); 
     db.insert(TABLE_NAME, null, values); 
     db.close(); 
    } 

    public int updateHabit(Habit habit) { 
     SQLiteDatabase db = this.getWritableDatabase(); 
     ContentValues values = new ContentValues(); 
     values.put(KEY_HABIT_NAME, habit.getHabit()); 
     values.put(KEY_HABIT_COUNT, habit.getCount()); 
     return db.update(TABLE_NAME, values, KEY_ID + " = ?", new String[]{String.valueOf(habit.getId())}); 
    } 

    public void deleteHabit(Habit habit) { 
     SQLiteDatabase db = this.getWritableDatabase(); 
     db.delete(TABLE_NAME, KEY_ID + " = ?", new String[]{String.valueOf(habit.getId())}); 
     db.close(); 
    } 

    public List<Habit> getAllHabit() { 
     List<Habit> habits = new ArrayList<>(); 
     String SELECT_QUERY = "SELECT * FROM " + TABLE_NAME; 
     SQLiteDatabase db = this.getWritableDatabase(); 
     Cursor cursor = db.rawQuery(SELECT_QUERY, null); 
     if (cursor.moveToFirst()) { 
      do { 
       Habit habit = new Habit(); 
       habit.setHabit(cursor.getString(1)); 
       habit.setCount(Integer.parseInt(cursor.getString(2))); 
       habit.setId(Integer.parseInt(cursor.getString(0))); 
       habits.add(habit); 
      } while (cursor.moveToNext()); 
     } 
     cursor.close(); 
     return habits; 
    } 
} 
+1

请将您的问题随附[mcve] –

+0

您究竟在哪里遇到问题? –

+0

使用AlertDialog添加新项目后,它不会显示在listView中。但是,如果我关闭了应用程序并重新打开它,则会显示新项目。我认为我的问题在MainActivity的updateList()中。但是,我不确定发生了什么问题。 –

回答

0

使用finishAffinity()这种方法 完成此活动,并试图完成紧接着的下 所有活动中具有相同的亲和力当前任务。

ActivityCompat.finishAffinity(this); 
2

我明白了。我不知道这是否是正确的方法,或者它只是一种解决方法。在updateList()方法,我改了行

habits = handler.getAllHabit();

habits.addAll(handler.getAllHabit());

现在马上右后我添加使用AlertDialog项目列表视图更新。

+1

是的,这是正确的方法Aakaash。做得好.. –

1

使用SimpleCursorAdapter并在适配器对象上调用changeCursor(newCursor),只要数据库中有更新。

申报cursorAdpater作为一个实例变量:

SimpleCursorAdapter cursorAdapter; 

然后在的onCreate,初始化的CursorAdapter并设置它的列表视图:

Cursor cursor = handler.getAllHabit();//Change the return type of your getAllHabit method to Cursor 
String[] from = new String[]{"name","count"};//database column names 
int[] to = new int[]{R.id.tvName,R.id.tvCount};//TextView id's from custom list row layout 
cursorAdapter = new SimpleCursorAdapter(this,R.layout.list_row,cursor,from,to,CursorAdapter.FLAG_AUTO_REQUERY); 
habitList.setAdapter(cursorAdapter); 

每当有数据库中的任何更新用,得到更新的数据放入一个新的光标,并在cursorAdapter上调用changeCursor()并传递新的光标。

Cursor newCursor = handler.getAllHabit(); 
cursorAdapter.changeCursor(newCursor);