2016-06-01 77 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);