How to read,add Database into ArrayList? - android

I'm new to Android Studio here. I don't know how to read and add database into Arraylist . Could you guys please help me with it :P ? I have already tried some methods, but It still didn't work #.# .
public class DatabaseHelper extends SQLiteOpenHelper
{
public static final String DATABASE_NAME = "ToDoList.db";
public static final String TABLE_NAME = "ToDoList_Table";
public static final String DATABASE_TABLE = "ToDo_DBTable";
public static final String COL_1 = "ID";
public static final String COL_2 = "TODO";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,TODO TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean insertData(String TODO) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2, TODO);
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1)
return false;
else
return true;
}
public ArrayList<String> getRecords(){
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<String> data=new ArrayList<String>();
Cursor cursor = db.query(TABLE_NAME, new String[]{COL_2},null, null, null, null, null);
String fieldToAdd=null;
while(cursor.moveToNext()){
fieldToAdd=cursor.getString(0);
data.add(fieldToAdd);
}
cursor.close();
return data;
}
}
public class MainActivity extends AppCompatActivity
{
DatabaseHelper TDdb;
ArrayList<String> todoItems;
ArrayAdapter<String> aTodoAdapter;
ListView lvItems;
EditText editTD;
Button btnAddItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
populateArrayItems();
editTD = (EditText) findViewById(R.id.tdEditText);
lvItems = (ListView) findViewById(R.id.lvItems);
btnAddItems = (Button) findViewById(R.id.tdAddItems);
AddData();
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setLogo(R.drawable.list_ingredients);
getSupportActionBar().setDisplayUseLogoEnabled(true);
lvItems.setAdapter(aTodoAdapter);
lvItems.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position,
long id) {
todoItems.remove(position);
aTodoAdapter.notifyDataSetChanged();
return true;
}
});
TDdb = new tdls.todolistapps.DatabaseHelper(this);
}
public void AddData()
{
btnAddItems.setOnClickListener(
new View.OnClickListener()
{
#Override
public void onClick(View view)
{
boolean isInserted = TDdb.insertData(editTD.getText().toString());
if(isInserted = true )
Toast.makeText(MainActivity.this,"Items Inserted",Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this,"Items not Inserted",Toast.LENGTH_LONG).show();
}
}
);
}
public void populateArrayItems()
{
todoItems = new ArrayList<String>();
todoItems.add("Item 1");
todoItems.add("Item 2");
todoItems.add("Item 3");
aTodoAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, todoItems );
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
menu.add("Email");
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;
}
return super.onOptionsItemSelected(item);
}
public void onAddItem(View v)
{
aTodoAdapter.add(editTD.getText().toString());
editTD.setText("");
}
}
Here is the picture, it said that Item Inserted but It won't display :'(

Try replacing following code
if(isInserted = true ){
todoItems.add(editTD.getText().toString());
aTodoAdapter.notifyDataSetChanged();
Toast.makeText(MainActivity.this,"Items Inserted",Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(MainActivity.this, "Items not Inserted", Toast.LENGTH_LONG).show();
}
As you need to update adapter as well after adding data to database.

At First change your getRecords() function like below:
public ArrayList<String> getRecords(){
open();
ArrayList<String> data = new ArrayList<>();
Cursor cursor = db.query(DATABASE_TABLE, new String[]{COL_2}, null, null, null, null, null, null);
if (cursor.moveToFirst()){
do {
data.add(cursor.getString(0));
} while (cursor.moveToNext());
}
close();
return data;
}

Related

Deleting an item from SQLite and listView

i want to delete item from a listView and SQLite database with contextMenu (press on item and hold, delete button appears, press it and item deletes) and my code doesnt remove anything. I tried when pressed on Delete, toast with text appears and it worked.
DBAdapter.java
public void delete(String name)throws SQLException {
SQLiteDatabase db = helper.getWritableDatabase();
if (db == null) {
return;
}
String[] whereArgs = new String[] { name };
db.delete("m_TB", "NAME"+ "=?", whereArgs);
db.close();
}
MainActivity.java
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add("Delete");
}
public boolean onContextItemSelected(MenuItem item) {
super.onContextItemSelected(item);
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
String name = info.toString();
if (item.getTitle().equals("Delete")) {
db.delete(name);
books.remove(item);
adapter.notifyDataSetChanged();
}
return true;
}
FULL CODE:
MainActivity.java
public class MainActivity extends AppCompatActivity {
ListView lv;
EditText nameTxt;
Button savebtn, retrievebtn;
ArrayList<String> books = new ArrayList<String>();
ArrayAdapter<String> adapter;
SearchView sv;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
final DBAdapter db = new DBAdapter(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nameTxt = (EditText) findViewById(R.id.editText);
savebtn = (Button) findViewById(R.id.saveBtn);
retrievebtn = (Button) findViewById(R.id.retrieveBtn);
lv = (ListView) findViewById(R.id.listView1);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, books);
registerForContextMenu(lv);
savebtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
db.openDB();
long result = db.add(nameTxt.getText().toString());
if (result > 0) {
nameTxt.setText("");
} else {
Toast.makeText(getApplicationContext(), "Failure", Toast.LENGTH_SHORT).show();
}
db.close();
}
});
retrievebtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
books.clear();
db.openDB();
Cursor c = db.getAllNames();
while (c.moveToNext()) {
String colIndex = c.getString(1);
books.add(colIndex);
}
lv.setAdapter(adapter);
db.close();
}
});
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), books.get(position), Toast.LENGTH_SHORT).show();
}
});
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add("Delete");
}
public boolean onContextItemSelected(MenuItem item) {
super.onContextItemSelected(item);
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
String name = info.toString();
if (item.getTitle().equals("Delete")) {
books.remove(info.position);
adapter.notifyDataSetChanged();
}
return true;
}
}
DBAdapter.java
public class DBAdapter {
static final String ROW_ID ="id";
static final String NAME ="name";
static final String TAG = "DBAdapter";
static final String DBNAME="m_DB";
static final String TBNAME="m_TB";
static final int DBVERSION='1';
static final String CREATE_TB="CREATE TABLE m_TB(id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "name TEXT NOT NULL);";
final Context c;
SQLiteDatabase db;
DBHelper helper;
public DBAdapter(Context ctx) {
this.c = ctx;
helper = new DBHelper(c);
}
private static class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context) {
super(context, DBNAME, null, DBVERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CREATE_TB);
} catch (SQLException e)
{
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w("DBAdapter","Upgrading DB");
db.execSQL("DROP TABLE IF EXISTS m_TB");
onCreate(db);
}
}
public DBAdapter openDB()
{
try {
db=helper.getWritableDatabase();
} catch (SQLException e)
{
Toast.makeText(c, e.getMessage(), Toast.LENGTH_LONG).show();
}
return this;
}
public void close()
{
helper.close();
}
public long add(String name)
{
try {
ContentValues cv = new ContentValues();
cv.put(NAME,name);
return db.insert(TBNAME,ROW_ID,cv);
} catch (SQLException e)
{
e.printStackTrace();
}
return 0;
}
public Cursor getAllNames()
{
String[] columns={ROW_ID,NAME};
return db.query(TBNAME,columns,null,null,null,null,null);
}
public void delete(String name)throws SQLException
{
SQLiteDatabase db = helper.getWritableDatabase();
if(db == null)
{
return;
}
String[] whereArgs = new String[]{name};
db.delete("m_TB", "NAME"+ "=?", whereArgs);
db.close();
}
}
You are not removing the item from the list books. If books is an ArrayList then
Change your line of code to
books.remove(info.position);
And to remove from database (If books is an ArrayList of custom type).
db.delete(books.get(info.position).name);
And if books is an arraylist of string then
db.delete(books.get(info.position));

SearchView in CustomAdapter

I want to implement an SearchView , inside my Listview , which items are getting from database ... I don't know if I have to use an EditText to make the search , or SearchView. If I write some letter , in my listView will be shown only thouse items wich are starting with thouse letters.
MainActivity :
public class MyActivity extends Activity implements AppCompatCallback {
private AppCompatDelegate delegate;
Toolbar toolbar;
private android.support.v7.app.ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout drawerLayout;
private CustomCursorAdapter customAdapter;
private PersonDataBaseHelper databaseHelper;
private static final int ENTER_DATA_REQUEST_CODE = 1;
private ListView listView;
View LiniarLayout;
private static final String TAG = MyActivity.class.getSimpleName();
TextView myalbums ;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
delegate = AppCompatDelegate.create(this, this);
//call the onCreate() of the AppCompatDelegate
delegate.onCreate(savedInstanceState);
//use the delegate to inflate the layout
delegate.setContentView(R.layout.main);
LiniarLayout = (View)findViewById(R.id.LiniarLayout);
//add the Toolbar
Toolbar toolbar= (Toolbar) findViewById(R.id.mytoolbar);
myalbums = (TextView) findViewById(R.id.myalbums);
delegate.setSupportActionBar(toolbar);
delegate.setTitle("Photo Album");
toolbar.getBackground().setAlpha(250);
drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mDrawerToggle = new android.support.v7.app.ActionBarDrawerToggle(this , drawerLayout,R.string.drawer_open,R.string.drawer_close);
drawerLayout.setDrawerListener(mDrawerToggle);
databaseHelper = new PersonDataBaseHelper(this);
listView = (ListView) findViewById(R.id.list_data);
// Database query can be a time consuming task ..
// so its safe to call database query in another thread
// Handler, will handle this stuff for you <img src="http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif?m=1129645325g" alt=":)" class="wp-smiley">
new Handler().post(new Runnable() {
#Override
public void run() {
customAdapter = new CustomCursorAdapter(MyActivity.this, databaseHelper.getAllData());
listView.setAdapter(customAdapter);
}
});
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "cliker on item" + position);
drawerLayout.closeDrawer(LiniarLayout);
TextView name1 = (TextView) parent.getChildAt(position- listView.getFirstVisiblePosition()).findViewById(R.id.tv_person_name);
String name = name1.getText().toString();
Toast.makeText(MyActivity.this, "You selected ''"+name+" ''",Toast.LENGTH_SHORT).show();
String name2 = "/"+name+"/";
String numeAplicatie = "/PhotoAlbum/";
File filepath = Environment.getExternalStorageDirectory();
File dir = new File(filepath.getAbsolutePath()
+numeAplicatie +name2);
if(!dir.exists()) {
dir.mkdirs();
}
Intent myIntent = new Intent(MyActivity.this, AlbumActivity.class);
myIntent.putExtra("nameAlbum",name2);
myIntent.putExtra("nameAlbum2",name);
startActivity(myIntent);
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(final AdapterView<?> parent, View view, final int position, final long id) {
AlertDialog.Builder builder = new AlertDialog.Builder(MyActivity.this);
TextView name1 = (TextView) parent.getChildAt(position - listView.getFirstVisiblePosition()).findViewById(R.id.tv_person_name);
final String name = name1.getText().toString();
Toast.makeText(MyActivity.this ,"You selected"+" ''"+name+"''", LENGTH_SHORT).show();
builder.setCancelable(false);
builder.setMessage("Are you sure you want to delete ''" + name + "'' ?");
builder.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
databaseHelper.deleteSingleRow(id);
customAdapter.changeCursor(databaseHelper.getAllData());
dialog.dismiss();
Toast.makeText(MyActivity.this ,"''" +name+"''"+" deleted",Toast.LENGTH_SHORT).show();
File filepath = Environment.getExternalStorageDirectory();
File dir = new File(filepath.getAbsolutePath()
+"/"+name+"/" );
deleteDir(dir);
}
});
builder.setTitle("Delete Album");
AlertDialog dialog = builder.create();
dialog.show();
return true;
}
});
Field mDragger = null;//mRightDragger for right obviously
try {
mDragger = drawerLayout.getClass().getDeclaredField(
"mLeftDragger");
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
mDragger.setAccessible(true);
ViewDragHelper draggerObj = null;
try {
draggerObj = (ViewDragHelper) mDragger.get(drawerLayout);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
Field mEdgeSize = null;
try {
mEdgeSize = draggerObj.getClass().getDeclaredField("mEdgeSize");
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
mEdgeSize.setAccessible(true);
int edge = 0;
try {
edge = mEdgeSize.getInt(draggerObj);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
try {
mEdgeSize.setInt(draggerObj, edge * 10);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
switch (item.getItemId()){
case R.id.action_setting:
startActivityForResult(new Intent(this, EnterDataActivity.class), ENTER_DATA_REQUEST_CODE);
}
//noinspection SimplifiableIfStatement
if(id==android.R.id.home){
if(drawerLayout.isDrawerOpen(LiniarLayout)){
drawerLayout.closeDrawer(LiniarLayout);
}else{drawerLayout.openDrawer(LiniarLayout);
if(databaseHelper.getAllData()==null){
myalbums.setText("Create Album");
}
}
}
return super.onOptionsItemSelected(item);
}
public void onClickEnterData(View btnAdd) {
startActivityForResult(new Intent(this, EnterDataActivity.class), ENTER_DATA_REQUEST_CODE);
}
public static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i=0; i<children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
// The directory is now empty so delete it
return dir.delete();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ENTER_DATA_REQUEST_CODE && resultCode == RESULT_OK) {
databaseHelper.insertData(data.getExtras().getString("tag_person_name"));
customAdapter.changeCursor(databaseHelper.getAllData());
drawerLayout.openDrawer(LiniarLayout);
}
}
#Override
public void onSupportActionModeStarted(ActionMode mode) {
}
#Override
public void onSupportActionModeFinished(ActionMode mode) {
}
#Nullable
#Override
public ActionMode onWindowStartingSupportActionMode(ActionMode.Callback callback) {
return null;
}
}
Cursor Adapter :
public class CustomCursorAdapter extends CursorAdapter {
public CustomCursorAdapter(Context context, Cursor c) {
super(context, c);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// when the view will be created for first time,
// we need to tell the adapters, how each item will look
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View retView = inflater.inflate(R.layout.single_row_item, parent, false);
return retView;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
// here we are setting our data
// that means, take the data from the cursor and put it in views
TextView textViewPersonName = (TextView) view.findViewById(R.id.tv_person_name);
textViewPersonName.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(1))));
}
}
And my DataBaseHelper :
public class PersonDataBaseHelper {
private static final String TAG = PersonDataBaseHelper.class.getSimpleName();
// database configuration
// if you want the onUpgrade to run then change the database_version
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "mydatabase.db";
// table configuration
private static final String TABLE_NAME = "person_table"; // Table name
private static final String PERSON_TABLE_COLUMN_ID = "_id"; // a column named "_id" is required for cursor
private static final String PERSON_TABLE_COLUMN_NAME = "person_name";
public static final String KEY_IMG = "image";
private DatabaseOpenHelper openHelper;
private SQLiteDatabase database;
// this is a wrapper class. that means, from outside world, anyone will communicate with PersonDatabaseHelper,
// but under the hood actually DatabaseOpenHelper class will perform database CRUD operations
public PersonDataBaseHelper(Context aContext) {
openHelper = new DatabaseOpenHelper(aContext);
database = openHelper.getWritableDatabase();
}
public void insertData (String aPersonName) {
// we are using ContentValues to avoid sql format errors
ContentValues contentValues = new ContentValues();
contentValues.put(PERSON_TABLE_COLUMN_NAME, aPersonName);
database.insert(TABLE_NAME, null, contentValues);
}
public Cursor getAllData () {
String buildSQL = "SELECT * FROM " + TABLE_NAME;
Log.d(TAG, "getAllData SQL: " + buildSQL);
return database.rawQuery(buildSQL,null);
}
public boolean deleteSingleRow(long rowId)
{
return database.delete(TABLE_NAME, PERSON_TABLE_COLUMN_ID + "=" + rowId, null) > 0;
}
// this DatabaseOpenHelper class will actually be used to perform database related operation
private class DatabaseOpenHelper extends SQLiteOpenHelper {
public DatabaseOpenHelper(Context aContext) {
super(aContext, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
// Create your tables here
String buildSQL = "CREATE TABLE " + TABLE_NAME + "( " + PERSON_TABLE_COLUMN_ID + " INTEGER PRIMARY KEY, " +
PERSON_TABLE_COLUMN_NAME + " TEXT )";
Log.d(TAG, "onCreate SQL: " + buildSQL);
sqLiteDatabase.execSQL(buildSQL);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
// Database schema upgrade code goes here
String buildSQL = "DROP TABLE IF EXISTS " + TABLE_NAME;
Log.d(TAG, "onUpgrade SQL: " + buildSQL);
sqLiteDatabase.execSQL(buildSQL); // drop previous table
onCreate(sqLiteDatabase); // create the table from the beginning
}
}
}

I got NullPointerException while i try to run this application for getting data from SQLite database

This is my main activity
I can't understand what's the wrong going on.while i try to run this,DDMS show NullPointerException.Please help me for find out the error.
public class MainActivity extends ActionBarActivity implements OnClickListener {
private Button btnAdd, btnView;
private TextView txtView;
private EditText etName;
private DBHelper dbHelper;
// private osList oslist;
private ArrayList<osList> allList;
private osList olist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setCustomActionBar();
btnAdd = (Button) findViewById(R.id.btnAdd);
btnView = (Button) findViewById(R.id.btnView);
txtView = (TextView) findViewById(R.id.txtView);
etName = (EditText) findViewById(R.id.etName);
btnAdd.setOnClickListener(this);
btnView.setOnClickListener(this);
}
private void setCustomActionBar() {
// TODO Auto-generated method stub
ActionBar actionBar = getSupportActionBar();
// actionBar.setBackgroundDrawable(new ColorDrawable(
// com.arifxdroid.listviewdemo.R.color.my_color));
// actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
// View view = getLayoutInflater()
// .inflate(R.layout.custom_actionbar, null);
// actionBar.setCustomView(view, new ActionBar.LayoutParams(
// ActionBar.LayoutParams.MATCH_PARENT,
// ActionBar.LayoutParams.MATCH_PARENT));
actionBar.setBackgroundDrawable(new ColorDrawable(R.color.my_color));
}
#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();
if (id == R.id.action_settings) {
return true;
} else if (id == R.id.action_add) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnAdd:
String givenName = etName.getText().toString();
olist = new osList(givenName);
long inserted = dbHelper.insertOS(olist);
if (inserted == -1) {
txtView.setText("Data can't be inserted");
} else {
Toast.makeText(getApplicationContext(), "sucessfully added",
Toast.LENGTH_SHORT).show();
}
break;
case R.id.btnView:
allList = dbHelper.getosList();
if (allList != null || allList.size() == 0) {
// txtView.setText("NO list found");
Toast.makeText(getApplicationContext(), "No List found",
Toast.LENGTH_SHORT).show();
} else {
for (osList l : allList) {
txtView.append("\n" + l.toString());
}
}
break;
default:
break;
}
}
}
This is SQLite helper class
public class DBHelper extends SQLiteOpenHelper {
public static final String DB_NAME = "ListOfOS";
public static final int VERSION = 1;
public static final String TABLE_NAME = "allOS";
public static final String ID_FIELD = "_ID";
public static final String NAME_FIELD = "osName";
public static final String TABLE_SQL = "CREATE TABLE " + TABLE_NAME + " ("
+ ID_FIELD + " INTEGER PRIMARY KEY AUTOINCREMENT, " + NAME_FIELD
+ " TEXT)";
public DBHelper(Context context) {
super(context, DB_NAME, null, VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(TABLE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
public long insertOS(osList oslist) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues value = new ContentValues();
value.put(NAME_FIELD, oslist.getOsName());
long inserted = db.insert(TABLE_NAME, "", value);
db.close();
return inserted;
}
public ArrayList<osList> getosList() {
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<osList> all = new ArrayList<osList>();
Cursor cursor = db.query(TABLE_SQL, null, null, null, null, null, null);
if (cursor != null) {
if (cursor.getCount() > 0) {
cursor.moveToFirst();
do {
String name = cursor.getString(cursor
.getColumnIndex(NAME_FIELD));
osList list = new osList(name);
all.add(list);
} while (cursor.moveToNext());
}
}
cursor.close();
db.close();
return all;
}
}
You need to initialize your Helper class, you havent done it.
dbHelper = new DBHelper(getApplicationContext());

Making a dynamic ListView clickable to change activity

My android app currently populates a ListView (in MainActivity) with the contents of a sqlite table. I would like to be able to click one of the created ListView Items and have it change activities to my EditNote activity, but also pass the database record relating to that ListView into EditNote, and populate the EditTexts.
My MainActivity is populates the ListView on load:
public class MainActivity extends ListActivity{
DatabaseHelper dbh;
ArrayList<String> listItems = new ArrayList<String>();
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbh = new DatabaseHelper(this);
dbh.open();
adapter = new ArrayAdapter<String> (this, android.R.layout.simple_list_item_1, listItems);
setListAdapter(adapter);
ArrayList<String[]> searchResult = new ArrayList<String[]>();
//EditText searchTitle = (EditText) findViewById(R.id.searchC);
listItems.clear();
searchResult = dbh.fetchNotes("");
//searchResult = dbh.fetchNotes(searchTitle.getText().toString());
String title = "", note = "";
for (int count = 0 ; count < searchResult.size() ; count++) {
note = searchResult.get(count)[1];
title = searchResult.get(count)[0];
listItems.add(title);
}
adapter.notifyDataSetChanged();
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
public void addNote(View v){
Intent newActivity = new Intent (this, AddingNote.class);
startActivity(newActivity);
finish();
}
}
My database class used to create the table and select statement:
public class DatabaseHelper {
private static final String DATABASE_NAME = "noteDatabase";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "note";
private OpenHelper mDbHelper;
private SQLiteDatabase mDb;
private final Context dbContext;
private static final String DATABASE_CREATE =
"CREATE TABLE " + TABLE_NAME + " (" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"title TEXT NOT NULL, " +
"note TEXT NOT NULL); ";
public DatabaseHelper(Context ctx) {
this.dbContext = ctx;
}
public DatabaseHelper open() throws SQLException {
mDbHelper = new OpenHelper(dbContext);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDbHelper.close();
}
public boolean createNote(String title, String note) {
ContentValues initialValues = new ContentValues();
initialValues.put("title", title);
initialValues.put("note", note);
return mDb.insert(TABLE_NAME, null, initialValues) > 0;
}
public boolean updateNote(long rowId, String title, String note) {
ContentValues args = new ContentValues();
args.put("title", title);
args.put("note", note);
return mDb.update(TABLE_NAME, args, "_id=" + rowId, null) > 0;
}
public void deleteAll() {
mDb.delete(TABLE_NAME, null, null);
}
public void deleteRecord(long rowID) {
mDb.delete(TABLE_NAME, "_rowId=" + rowID, null);
}
public ArrayList<String[]> fetchNotes(String title) throws SQLException {
ArrayList<String[]> myArray = new ArrayList<String[]>();
int pointer = 0;
Cursor mCursor = mDb.query(TABLE_NAME, new String[] {"_id", "title",
"note"}, null, null,
null, null, "_id");
int titleColumn = mCursor.getColumnIndex("title");
int noteColumn = mCursor.getColumnIndex("note");
if (mCursor != null){
if (mCursor.moveToFirst()){
do {
myArray.add(new String[3]);
myArray.get(pointer)[0] = mCursor.getString(titleColumn);
myArray.get(pointer)[1] = mCursor.getString(noteColumn);
//increment our pointer variable.
pointer++;
} while (mCursor.moveToNext()); // If possible move to the next record
} else {
myArray.add(new String[3]);
myArray.get(pointer)[0] = "NO RESULTS";
myArray.get(pointer)[1] = "";
}
}
return myArray;
}
public ArrayList<String[]> selectAll() {
ArrayList<String[]> results = new ArrayList<String[]>();
int counter = 0;
Cursor cursor = this.mDb.query(TABLE_NAME, new String[] { "id", "forename", "surname", "age" }, null, null, null, null, "surname desc");
if (cursor.moveToFirst()) {
do {
results.add(new String[3]);
results.get(counter)[0] = cursor.getString(0).toString();
results.get(counter)[1] = cursor.getString(1).toString();
results.get(counter)[2] = cursor.getString(2).toString();
results.get(counter)[3] = cursor.getString(3).toString();
counter++;
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return results;
}
private static class OpenHelper extends SQLiteOpenHelper {
OpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
}
My list view XML (within activity_main.xml):
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/container" >
</ListView>
I'm pretty new to android development, so any help will be gratefully appreciated. Thank you.
Set an onClickListener to your ListView and start an Intent pointing to your EditNote activity which gets the data using:
getIntent().getStringExtra(...);
Example:
MainActivity:
getListView().setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i = new Intent(this, EditNote.class);
i.putExtra("listItem", listItems[position]);
startActivity(i);
}
});
EditNote:
String listItem = getIntent().getStringExtra("listItem");
Is this what you're looking for?

Deleting from SQL database android

I have a list view and when the user clicks a specific item a contextual action mode is displayed with only one item in it (that is supposed to delete it). However, when I click it, the database is not updated (the item is still on the list). Could anyone help me ?
In MainActivity:
final Context context = this;
ArrayAdapter<String> arrayAdapter;
ArrayList<String> listItems = new ArrayList<String>();
ListView lv;
protected Object mActionMode;
int catPos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
CategoryDatabase entry = new CategoryDatabase(MainActivity.this);
entry.open();
List<String> all = entry.getAllCategory();
if(all.size()> 0){
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",Toast.LENGTH_LONG).show();
}
entry.close();
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
catPos = position;
if (mActionMode != null) {
return false;
}
// Start the CAB using the ActionMode.Callback defined above
mActionMode = MainActivity.this
.startActionMode(mActionModeCallback);
view.setSelected(true);
return true;
}
});
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_delete_cat:
// shareCurrentItem();
CategoryDatabase entry = new CategoryDatabase(MainActivity.this);
entry.open();
entry.deleteCat(catPos);
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);
entry.close();
mode.finish(); // Action picked, so close the CAB
return true;
default:
return false;
}
}
in Actual Database:
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);
}
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;
}
public void deleteCat(int catPos) {
ourDatabase.delete(DATABASE_TABLE, KEY_ROWID + "=" + catPos, null);
}
}
Deleting as "entry.deleteCat(catPos);" is not right. If You use Your catPos, which is the position inside the listView, it will not delete the entry from database. You made an INTEGER_PRIMARY_KEY_AUTOINCREMENT inside Your Database, so this Integer will generated automatically and can differ from Your position Integer. What You have to do is, to make a query method inside Your Database where You get even the ID from Your DB-Entry. Then You could call
entry.deleteCat(databaseId);

Categories

Resources