My application is based on displaying a dialog box when the user enters the "add category" button. It then should save data into an SQL Database and populate a list view with each item the user adds. I chose SQL database because I want the data to be saved when the user ends the app. How do I actually populate the list view with those items ? Here is what I have so far:
public class CategoryDatabase {
public static final String KEY_ROWID = "_id";
public static final String KEY_CATEGORY = "category";
private static final String DATABASE_NAME = "DBCategory";
private static final String DATABASE_TABLE = "categoryTable";
private static final int DATABASE_VERSION = 1;
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
public CategoryDatabase(Context c){
ourContext = c;
}
public CategoryDatabase open() throws SQLException{
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close(){
ourHelper.close();
}
private static class DbHelper extends SQLiteOpenHelper{
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_CATEGORY + " TEXT NOT NULL);"
);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public long createEntry(String category) {
ContentValues cv = new ContentValues();
cv.put(KEY_CATEGORY, category);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
}
and the Main Activity:
public class MainActivity extends Activity {
final Context context = this;
ArrayAdapter<String> arrayAdapter;
ArrayList<String> listItems = new ArrayList<String>();
ListView lv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lv = (ListView)findViewById(R.id.listView1);
arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, listItems);
lv.setAdapter(arrayAdapter);
}
@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) {
switch(item.getItemId()){
case R.id.menu_add_cat:
LayoutInflater li = LayoutInflater.from(context);
View promptAdd = li.inflate(R.layout.prompt_add, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
//set prompts.xml to alertDialogBuilder
alertDialogBuilder.setView(promptAdd);
final EditText etAddCat = (EditText)promptAdd.findViewById(R.id.etDialogInput);
//set a dialog message
alertDialogBuilder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
/*
* add a cat here
* if(null != input && input.length() > 0){
listItems.add(input);
arrayAdapter.notifyDataSetChanged();
}else{
Toast.makeText(getApplicationContext(), "Please enter a new category", Toast.LENGTH_LONG).show();
}
*/
boolean didItWork = true;
try{
String category = etAddCat.getText().toString();
CategoryDatabase entry = new CategoryDatabase(MainActivity.this);
entry.open();
entry.createEntry(category);
entry.close();
}catch(Exception e){
didItWork = false;
String error = e.toString();
Dialog d = new Dialog(MainActivity.this);
d.setTitle("Dang it ! ");
TextView tv = new TextView(MainActivity.this);
tv.setText(error);
d.setContentView(tv);
d.show();
}finally{
if(didItWork){
Dialog d = new Dialog(MainActivity.this);
d.setTitle("Heck yea ! ");
TextView tv = new TextView(MainActivity.this);
tv.setText("Success");
d.setContentView(tv);
d.show();
}
}
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
break;
}
//return super.onOptionsItemSelected(item);
return true;
}
}// end of MainActivity
Create a function getAllCategory()
in CategoryDatabase
class.
public List<String> getAllCategory() {
List<String> List = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + DATABASE_TABLE;
Cursor cursor = ourDatabase.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
List.add(cursor.getString(1));
} while (cursor.moveToNext());
}
return List;
}
To populate items to listview.
In your MainActivity
say on button click.
CategoryDatabase entry = new CategoryDatabase(MainActivity.this);
entry.open();
List<String> all = entry.getAllCategory();
lv = (ListView)findViewById(R.id.listView1);
arrayAdapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1, all);
lv.setAdapter(arrayAdapter);
Edit :
In onCreate
CategoryDatabase entry = new CategoryDatabase(MainActivity.this);
entry.open();
List<String> all = entry.getAllCategory();
if(all.size()>0) // check if list contains items.
{
lv = (ListView)findViewById(R.id.listView1);
arrayAdapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1, all);
lv.setAdapter(arrayAdapter);
}
else
{
Toast.makeText(MainActivity.this,"No items to display",1000).show();
}