Deleting an item from SQLite and listView - android

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));

Related

SQLite filtering and searching data

Hello I have SQLite application based on SQLite database and I want it to have search/filter option. When i tried to use
adapter.getFilter().filter(query)
It filtered, but after filtering once,i can't do any more actions(add or delete items). Maybe someone have ideas how can I make search ?
DBAdapter.java
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);
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
ListView lv;
EditText nameTxt;
Button savebtn,retrievebtn;
ArrayList<String> books = new ArrayList<String>();
ArrayAdapter<String> adapter;
#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_selectable_list_item,books);
final DBAdapter db = new DBAdapter(this);
savebtn.setOnClickListener(new View.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 View.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 AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(),books.get(position), Toast.LENGTH_SHORT).show();
}
});
}

How to read,add Database into ArrayList?

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;
}

Deleting items in a listView and database

I am trying to delete objects in a listView and database at the same time after you have clicked the item in the listView. I'm tying to make it open an alert dialog before deleting the item. I have read many other stack overflow questions about this such as :
how can i delete an item from listview and also database
delete a specific item from listview stored in database in android application
Delete item from database - ListView - Android
And many others...none of them I find very helpful. Any suggestions?
Main_Activity:
public class New_Recipe extends AppCompatActivity {
Button add, done;
EditText Recipe_Name, Recipe_Item, Recipe_Steps;
String search;
WebView webView;
DatabaseHelper databaseHelper;
ListView ItemsList;
Context context = this;
SQLiteDatabase sqLiteDatabase;
Cursor cursor;
RecipeListAdapter listAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new__recipe);
setTitle("New Recipe");
add = (Button) findViewById(R.id.button2);
done = (Button) findViewById(R.id.button);
Recipe_Name = (EditText) findViewById(R.id.editText);
Recipe_Item = (EditText) findViewById(R.id.editText2);
Recipe_Steps = (EditText) findViewById(R.id.editText3);
webView = (WebView) findViewById(R.id.webView);
ItemsList = (ListView) findViewById(R.id.listView);
listAdapter = new RecipeListAdapter(getApplicationContext(), R.layout.recipe_textview);
context = this;
AddData();
}
//When the add button is pressed
public void AddData() {
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String item = Recipe_Item.getText().toString();
databaseHelper = new DatabaseHelper(context);
sqLiteDatabase = databaseHelper.getWritableDatabase();
databaseHelper.addItems(item, sqLiteDatabase);
Toast.makeText(getBaseContext(), "Item inserted", Toast.LENGTH_LONG).show();
databaseHelper.close();
ItemsList.setAdapter(listAdapter);
databaseHelper = new DatabaseHelper(getApplicationContext());
sqLiteDatabase = databaseHelper.getReadableDatabase();
cursor = databaseHelper.getItems(sqLiteDatabase);
if (cursor.moveToFirst()) {
do {
String items;
items = cursor.getString(0);
RecipeDataProvider dataProvider = new RecipeDataProvider(items);
listAdapter.add(dataProvider);
} while (cursor.moveToNext());
}
}
});
}
public void onSearch(View v) {
search = "Recipes";
webView.loadUrl("https://www.google.com/search?q=" + search);
}
#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_new__recipe, 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;
}
return super.onOptionsItemSelected(item);
}
DatabaseHelper class:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 5;
public static final String DATABASE_NAME = "Recipes.db";
public static final String CREATE_QUERRY = "create table " + RecipeContract.RecipeEntry.TABLE_NAME + "( _ID INTEGER PRIMARY KEY, NAME text, ITEMS text, STEPS text)";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
Log.d("Recipe Database", "Database should be made!");
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_QUERRY);
Log.d("Recipe Database", "Table should be made!");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void addItems(String items, SQLiteDatabase db)
{
ContentValues values = new ContentValues();
values.put(RecipeContract.RecipeEntry.COL2,items);
db.insert(RecipeContract.RecipeEntry.TABLE_NAME,null,values);
Log.e("Recipe Database","Item should be added to the table!");
}
public Cursor getItems(SQLiteDatabase db)
{
Cursor cursor;
String[] projections = {RecipeContract.RecipeEntry.COL2};
cursor = db.query(RecipeContract.RecipeEntry.TABLE_NAME,projections,null,null,null,null,null);
return cursor;
}
ListViewAdapter:
public class RecipeListAdapter extends ArrayAdapter {
List list = new ArrayList();
public RecipeListAdapter(Context context, int resource) {
super(context, resource);
}
static class LayoutHandler
{
TextView ITEM;
}
#Override
public void add(Object object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return super.getCount();
}
#Override
public Object getItem(int position) {
return super.getItem(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
LayoutHandler layoutHandler;
if (row == null)
{
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.recipe_textview,parent,false);
layoutHandler = new LayoutHandler();
layoutHandler.ITEM = (TextView) row.findViewById(R.id.tx_items);
row.setTag(layoutHandler);
} else {
layoutHandler = (LayoutHandler) row.getTag();
}
RecipeDataProvider dataProvider = (RecipeDataProvider) this.getItem(position);
layoutHandler.ITEM.setText(dataProvider.getItems().toString());
return row;
}
EDIT: my updated Main_Activity class
public class New_Recipe extends AppCompatActivity {
Button add, done;
EditText Recipe_Name, Recipe_Item, Recipe_Steps;
String search;
WebView webView;
DatabaseHelper databaseHelper;
ListView ItemsList;
Context context = this;
SQLiteDatabase sqLiteDatabase;
Cursor cursor;
RecipeListAdapter listAdapter;
List<New_Recipe> list = new ArrayList<>();
private int id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new__recipe);
setTitle("New Recipe");
add = (Button) findViewById(R.id.button2);
done = (Button) findViewById(R.id.button);
Recipe_Name = (EditText) findViewById(R.id.editText);
Recipe_Item = (EditText) findViewById(R.id.editText2);
Recipe_Steps = (EditText) findViewById(R.id.editText3);
webView = (WebView) findViewById(R.id.webView);
ItemsList = (ListView) findViewById(R.id.listView);
listAdapter = new RecipeListAdapter(getApplicationContext(), R.layout.recipe_textview);
context = this;
AddData();
ItemsList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Object getSelectedItem = list.get(position);
databaseHelper.deleteItem(getSelectedItem);
listAdapter.deleteitem(getSelectedItem);
return true;
}
});
}
public New_Recipe(){
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
You can use this method for deleting a row from DatabaseHelper class :
public void deleteItem(Object item) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, KEY_ID + " = ?",
new String[]{String.valueOf(item.getId())});
db.close();
}
And then you need also one method for deleting object from adapter :
public void deleteItem(Object item) {
listArray.remove(item);
notifyDataSetChanged();
}
Now you can call all this method in activity like this :
Let's say that you want to delete all this by clicking long on list item :
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int pos, long id) {
Object getSelectedItem = arrayList.get(pos);
dataBaseHelper.deleteItem(getSelectedItem);
adapter.deleteItem(getSelectedItem);
return true;
}
});
UPDATED:
You need before you try to call method getId() to create that method in your class. So you need to create get and setter methods in your class, something like this:
STEP BY STEP:
Change your class New_Recipe to MainActivity. If you are getting an error, just highlight that error and there you will see "rename file".
Create a new class outside your main class and call it NewRecipe:
public class NewRecipe {
private int id;
private String title;
public NewRecipe() {
// empty constructor
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
And now you can do everything i have explained earlier.
You need a function deletein DatabaseHelper class
public boolean delete(long rowId) {
return db.delete(TABLE_NAME, KEY_ROWID + "=" + rowId, null) > 0;
}
You need a function in the Activity deleteItem() similar to addItems()
public void deleteItem(){
//Based on some logic,find the rowID of the table which needs to be deleted and call delete function of DatabaseHelper class.
}
Similarily in your ListViewAdapter, you need to define a method delete
public void delete(Object object) {
list.remove(object);
//To update the ListView in Android
this.notifyDataSetChanged();
}

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
}
}
}

Listview empty after insert a field in db?

I was looking for an example/tutorial to insert datas in a sqlLite db and display the datas in a listview. Well this is a good example: http://androidsolution4u.blogspot.it/2013/09/android-populate-listview-from-sqlite.html And it works. I implemented the code in mine and works. The problem is that if i want insert another one filed nothing appears in the listview and the activity is empty.I added a field called address as string like the others and in every part of code i added what is need copying from the others (of course changing the names). But when i try to add the item not appears. Of course i update the xml files with new field. I can't write the whole code because it's too much. But if someone can help me to find a way out i'll write the part of code required. Thanks
EDIT: the code is equal at the example but with the field i need to add.
The DisplayActivity
public class DisplayActivity extends Activity {
private DbHelper mHelper;
private SQLiteDatabase dataBase;
private ArrayList<String> userId = new ArrayList<String>();
private ArrayList<String> user_fName = new ArrayList<String>();
private ArrayList<String> user_lName = new ArrayList<String>();
private ArrayList<String> user_address = new ArrayList<String>();
private ListView userList;
private AlertDialog.Builder build;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_activity);
userList = (ListView) findViewById(R.id.List);
mHelper = new DbHelper(this);
//add new record
findViewById(R.id.btnAdd).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), AddActivity.class);
i.putExtra("update", false);
startActivity(i);
}
});
//click to update data
userList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Intent i = new Intent(getApplicationContext(), AddActivity.class);
i.putExtra("Fname", user_fName.get(arg2));
i.putExtra("Lname", user_lName.get(arg2));
i.putExtra("address", user_address.get(arg2));
i.putExtra("ID", userId.get(arg2));
i.putExtra("update", true);
startActivity(i);
}
});
//long click to delete data
userList.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, final int arg2, long arg3) {
build = new AlertDialog.Builder(DisplayActivity.this);
build.setTitle("Delete " + user_fName.get(arg2) + " " + user_lName.get(arg2) + " " + user_address(arg2));
build.setMessage("Do you want to delete ?");
build.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText( getApplicationContext(),
user_fName.get(arg2) + " "
+ user_lName.get(arg2)
+ user_address.get(arg2)
+ " is deleted.", 3000).show();
dataBase.delete(
DbHelper.TABLE_NAME,
DbHelper.KEY_ID + "="
+ userId.get(arg2), null);
displayData();
dialog.cancel();
}
});
build.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = build.create();
alert.show();
return true;
}
});
}
#Override
protected void onResume() {
displayData();
super.onResume();
}
/**
* displays data from SQLite
*/
private void displayData() {
dataBase = mHelper.getWritableDatabase();
Cursor mCursor = dataBase.rawQuery("SELECT * FROM " + DbHelper.TABLE_NAME, null);
userId.clear();
user_fName.clear();
user_lName.clear();
user_address.clear();
if (mCursor.moveToFirst()) {
do {
userId.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
user_fName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_FNAME)));
user_lName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_LNAME)));
} while (mCursor.moveToNext());
}
DisplayAdapter disadpt = new DisplayAdapter(DisplayActivity.this,userId, user_fName, user_lName, user_address);
userList.setAdapter(disadpt);
mCursor.close();
}
}
The DisplayAdapter
public class DisplayAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<String> id;
private ArrayList<String> firstName;
private ArrayList<String> lastName;
private ArrayList<String> address;
public DisplayAdapter(Context c, ArrayList<String> id,ArrayList<String> fname, ArrayList<String> lname, ArrayList<String> address) {
this.mContext = c;
this.id = id;
this.firstName = fname;
this.lastName = lname;
this.address = address;
}
public int getCount() {
// TODO Auto-generated method stub
return id.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView(int pos, View child, ViewGroup parent) {
Holder mHolder;
LayoutInflater layoutInflater;
if (child == null) {
layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.listcell, null);
mHolder = new Holder();
mHolder.txt_id = (TextView) child.findViewById(R.id.txt_id);
mHolder.txt_fName = (TextView) child.findViewById(R.id.txt_fName);
mHolder.txt_lName = (TextView) child.findViewById(R.id.txt_lName);
mHolder.txt_address = (TextView) child.findViewById(R.id.txt_address);
child.setTag(mHolder);
} else {
mHolder = (Holder) child.getTag();
}
mHolder.txt_id.setText(id.get(pos));
mHolder.txt_fName.setText(firstName.get(pos));
mHolder.txt_lName.setText(lastName.get(pos));
mHolder.txt_address.setText(address.get(pos));
return child;
}
public class Holder {
TextView txt_id;
TextView txt_fName;
TextView txt_lName;
TextView txt_address;
}
}
The DbHelper
public class DbHelper extends SQLiteOpenHelper {
static String DATABASE_NAME="userdata";
public static final String TABLE_NAME="user";
public static final String KEY_FNAME="fname";
public static final String KEY_LNAME="lname";
public static final String KEY_ID="id";
public static final String KEY_ADDRESS="address";
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY KEY, "+KEY_FNAME+" TEXT, "+KEY_LNAME+" TEXT, "+KEY_ADDRESS+" TEXT)";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
}
And the AddActivity
public class AddActivity extends Activity implements OnClickListener {
private Button btn_save;
private EditText edit_first,edit_last,edit_address;
private DbHelper mHelper;
private SQLiteDatabase dataBase;
private String id,fname,lname,address;
private boolean isUpdate;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_activity);
btn_save=(Button)findViewById(R.id.save_btn);
edit_first=(EditText)findViewById(R.id.frst_editTxt);
edit_last=(EditText)findViewById(R.id.last_editTxt);
edit_address=(EditText)findViewById(R.id.address_editTxt);
isUpdate=getIntent().getExtras().getBoolean("update");
if(isUpdate)
{
id=getIntent().getExtras().getString("ID");
fname=getIntent().getExtras().getString("Fname");
lname=getIntent().getExtras().getString("Lname");
address=getIntent().getExtras().getString("address");
edit_first.setText(fname);
edit_last.setText(lname);
edit_address.setText(address);
}
btn_save.setOnClickListener(this);
mHelper=new DbHelper(this);
}
// saveButton click event
public void onClick(View v) {
fname=edit_first.getText().toString().trim();
lname=edit_last.getText().toString().trim();
address=edit_address.getText().toString().trim();
if(fname.length()>0 && lname.length()>0 && address.length()>0)
{
saveData();
}
else
{
AlertDialog.Builder alertBuilder=new AlertDialog.Builder(AddActivity.this);
alertBuilder.setTitle("Invalid Data");
alertBuilder.setMessage("Please, Enter valid data");
alertBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertBuilder.create().show();
}
}
/**
* save data into SQLite
*/
private void saveData(){
dataBase=mHelper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(DbHelper.KEY_FNAME,fname);
values.put(DbHelper.KEY_LNAME,lname );
values.put(DbHelper.KEY_ADDRESS,address );
System.out.println("");
if(isUpdate)
{
//update database with new data
dataBase.update(DbHelper.TABLE_NAME, values, DbHelper.KEY_ID+"="+id, null);
}
else
{
//insert data into database
dataBase.insert(DbHelper.TABLE_NAME, null, values);
}
//close database
dataBase.close();
finish();
}
}
That's all. I can't find the problem. Helps?
Forgotten in displayData() user_address.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ADDRESS)));

Categories

Resources