I am creating an android application that consists of a list view populated by the data from the database.
Here I need to delete the data from the database as well as the list view and refresh the list view.
I used both notifyOnDataSetChanged() and notifyOnDataSetInvalidated() but
it wont work for me please help me with this
package com.developer.milanandroid;
import android.app.ActionBar;
import android.app.Activity;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.gc.materialdesign.widgets.Dialog;
import com.milan.emptylayout.EmptyLayout;
import com.milan.lib.progressgenarator.lib.ProgressGenerator;
import com.milan.lib.progressgenarator.lib.ProgressGenerator.OnCompleteListener;
import com.milan.swipemenulistview.SwipeMenu;
import com.milan.swipemenulistview.SwipeMenuCreator;
import com.milan.swipemenulistview.SwipeMenuItem;
import com.milan.swipemenulistview.SwipeMenuListView;
import com.milan.swipemenulistview.SwipeMenuListView.OnMenuItemClickListener;
import com.processbutton.lib.milan.ActionProcessButton;
public class DatabaseListView extends Activity implements OnCompleteListener {
MediaPlayer media_player;
ActionProcessButton fetch_database;
SwipeMenuListView database_results;
LoginDataBaseAdapter logindatabase_adapter;
SimpleCursorAdapter cursoradapter;
Cursor cursor;
TextView username_txt,password_txt;
String user_name_string,password_string;
String text;
Dialog dialog;
private EmptyLayout empty_layout;
View.OnClickListener emptyClickListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.databaselistview);
View.OnClickListener mErrorClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
fetch_database.setText("Checking...");
empty_layout.showLoading();
ProgressGenerator pg = new ProgressGenerator(DatabaseListView.this);
pg.start(fetch_database);
}
};
emptyClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(DatabaseListView.this, "Try again button clicked", Toast.LENGTH_LONG).show();
}
};
ActionBar actionbar = getActionBar();
actionbar.hide();
View v;
LinearLayout linear = (LinearLayout)findViewById(R.id.linearLayout1);
username_txt = (TextView)linear.getChildAt(0);
password_txt = (TextView)linear.getChildAt(0);
user_name_string = username_txt.getText().toString();
password_string = password_txt.getText().toString();
fetch_database = (ActionProcessButton)findViewById(R.id.Button_Fetch_from_Database);
database_results = (SwipeMenuListView)findViewById(R.id.listview_database);
final ProgressGenerator progressGenerator = new ProgressGenerator(DatabaseListView.this);
logindatabase_adapter = new LoginDataBaseAdapter(DatabaseListView.this);
empty_layout = new EmptyLayout(DatabaseListView.this, database_results);
empty_layout.setErrorButtonClickListener(mErrorClickListener);
fetch_database.setMode(ActionProcessButton.Mode.PROGRESS);
fetch_database.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
progressGenerator.start(fetch_database);
fetch_database.setText("Checking...");
fetch_database.setEnabled(false);
empty_layout.showLoading();
media_player = MediaPlayer.create(DatabaseListView.this, R.raw.retrievingfromdatabase);
media_player.start();
String[] from = {LoginDataBaseAdapter.USER_NAME,LoginDataBaseAdapter.USER_PASSWORD};
int[] to = {R.id.txt_username,R.id.txt_pasword};
cursor = logindatabase_adapter.feching_Data();
cursoradapter = new SimpleCursorAdapter(DatabaseListView.this, R.layout.listcell, cursor, from, to);
cursoradapter.notifyDataSetChanged();
//registerForContextMenu(database_results);
}
});
SwipeMenuCreator swipe_list_view = new SwipeMenuCreator() {
#Override
public void create(SwipeMenu menu) {
SwipeMenuItem open_swipemenu = new SwipeMenuItem(DatabaseListView.this);
open_swipemenu.setBackground(new ColorDrawable(Color.rgb(0x9B,0x33,0xF0)));
open_swipemenu.setWidth(dp2px(90));
open_swipemenu.setIcon(R.drawable.databasedelete);
menu.addMenuItem(open_swipemenu);
}
};
database_results.setMenuCreator(swipe_list_view);
database_results.setOnMenuItemClickListener(new OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(final int position, SwipeMenu menu, int index) {
switch(index) {
case 0:
dialog = new Dialog(DatabaseListView.this, "Delete Record", "Do you want to delete Record from database");
dialog.setCancelable(false);
dialog.setOnAcceptButtonClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
cursor = (Cursor) database_results.getItemAtPosition(position);
final int item_id = cursor.getInt(cursor.getColumnIndex(LoginDataBaseAdapter.ID));
cursor.getString(cursor.getColumnIndex(LoginDataBaseAdapter.USER_NAME));
cursor.getString(cursor.getColumnIndex(LoginDataBaseAdapter.USER_PASSWORD));
logindatabase_adapter.deleteEntry(item_id);
//database_results.removeViewAt(position);
//cursoradapter.notifyDataSetChanged();
database_results.invalidateViews();
}
});
dialog.show();
}
return false;
}
});
}
protected int dp2px(int dp) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
getResources().getDisplayMetrics());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.database_list_view, 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);
}
#Override
public void onComplete() {
if(cursor!=null && cursor.getCount()>0){
database_results.setAdapter(cursoradapter);
fetch_database.setEnabled(false);
fetch_database.setText("SUCCESS");
}
else{
/*fetch_database.setEnabled(false);
fetch_database.setText("OOPS");
fetch_database.setBackgroundColor(Color.parseColor("#ffb74d"));
final Dialog dialog_database = new Dialog(DatabaseListView.this, "Database Records", "No Records was found in the database");
dialog_database.setOnAcceptButtonClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog_database.cancel();
}
});
dialog_database.show();*/
fetch_database.setText("OOPS");
fetch_database.setBackgroundColor(Color.parseColor("#ffb74d"));
empty_layout.showError();
}
}
}
This is my LoginDatabase adpater:
package com.developer.milanandroid;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.view.View;
public class LoginDataBaseAdapter
{
//Database name
static final String DATABASE_NAME = "MilanloginRegistration.db";
static final int DATABASE_VERSION = 1;
public static final int NAME_COLUMN = 1;
// TODO: Create public field for each column in your table.
// SQL Statement to create a new database.
public static final String TABLE_NAME="MilanLoginregistration";
public static final String ID="_id";
public static final String USER_NAME="USERNAME";
public static final String USER_PASSWORD ="PASSWORD";
static final String DATABASE_CREATE = "create table "+ TABLE_NAME +
"( " +ID+" integer primary key autoincrement,"+"USERNAME text not null,"+USER_PASSWORD+" text not null); ";
// Variable to hold the database instance
public SQLiteDatabase db;
// Context of the application using the database.
private final Context context;
// Database open/upgrade helper
private DataBaseHelper dbHelper;
public LoginDataBaseAdapter(Context _context)
{
context = _context;
dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public LoginDataBaseAdapter open() throws SQLException
{
db = dbHelper.getWritableDatabase();
return this;
}
public void close()
{
db.close();
}
public SQLiteDatabase getDatabaseInstance()
{
return db;
}
public LoginDataBaseAdapter opentoRead() throws android.database.SQLException{
dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
db = dbHelper.getReadableDatabase();
return this;
}
public LoginDataBaseAdapter opentoWrite() throws android.database.SQLException{
dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
db = dbHelper.getWritableDatabase();
return this;
}
public void Close(){
dbHelper.close();
}
public void insertEntry(String username,String password)
{
ContentValues newValues = new ContentValues();
newValues.put("USERNAME",username);
newValues.put("PASSWORD",password);
// Insert the row into your table
db.insert("MilanLoginregistration",null,newValues);
///Toast.makeText(context, "Reminder Is Successfully Saved", Toast.LENGTH_LONG).show();
}
public int deleteAll(){
return db.delete(TABLE_NAME, null, null);
}
public void deleteEntry(int id){
//String id=String.valueOf(ID);
db.delete(TABLE_NAME, ID+"="+id, null);
// Toast.makeText(context, "Number fo Entry Deleted Successfully : "+numberOFEntriesDeleted, Toast.LENGTH_LONG).show();
}
public Cursor queue_all(){
String[] columns = new String[]{ID,"USERNAME","PASSWORD"};
Cursor cursor_queue_all =db.query(TABLE_NAME, columns, null, null, null, null, null);
return cursor_queue_all;
}
public Cursor feching_Data(){
String[] columns = {ID,USER_NAME,USER_PASSWORD};
db = dbHelper.getWritableDatabase();
Cursor cursor = db.query(TABLE_NAME, columns,null,null,null,null,null);
return cursor;
}
public String getSinlgeEntry(String userName)
{
Cursor cursor=db.query("MilanLoginregistration", null, " USERNAME=?", new String[]{userName}, null, null, null);
if(cursor.getCount()<1) // UserName Not Exist
{
cursor.close();
return "NOT EXIST";
}
cursor.moveToFirst();
String password= cursor.getString(cursor.getColumnIndex("PASSWORD"));
//cursor.close();
return password;
}
public String checkSinlgeEntry(String userName)
{
Cursor cursor=db.query("MilanLoginregistration", null, " USERNAME=?", new String[]{userName}, null, null, null);
if(cursor.getCount()>=1) // UserName Exist
{
cursor.close();
return "NOT EXIST";
}
// cursor.close();
return "";
}
public void updateEntry(String user_name,String pasword)
{
// Define the updated row content.
ContentValues updatedValues = new ContentValues();
// Assign values for each row.
updatedValues.put("USERNAME", user_name);
updatedValues.put("PASSWORD",pasword);
String where="USERNAME = ?";
db.update("MilanLoginregistration",updatedValues, where, new String[]{user_name});
}
/*public void Display(View v){
Cursor c = db.rawQuery("select * from MilanloginRegistration", null);
admin_settings_child.text_fetched_database_results.setText("");
c.moveToFirst();
do{
String username = c.getString(c.getColumnIndex("USERNAME"));
String password = c.getString(1);
admin_settings_child.text_fetched_database_results.append("USERNAME::-->"+username+"PASSWORD::-->"+password+"\n");
}while(c.moveToNext());
}*/
}
Kindly post the code of your adapter as well. in the above code you are deleting the data from other adapter and notifying other adapter for data set changed. i.e in following lines I can't see where cursoradapter is actually being updated.
logindatabase_adapter.deleteEntry(item_id);
cursoradapter.notifyDataSetChanged();
cursoradapter.notifyDataSetInvalidated();
also you can try this.
listview.getAdapter().notifyDataSetChanged();
For proper implementing datasetchanged functionality you need to create custom adapter other wise you just setlist adapter every time your data is being changed.i.e
listeview.setAdapter(modifiedAdapter);
listview.getAdapter.notifyDataSetChanged();
Edit 1:
as you are using simple cursor adapter you need to add following lines after deleting the entry:
logindatabase_adapter.deleteEntry(item_id);
cursor = logindatabase_adapter.feching_Data();
//database_results.removeViewAt(position);
cursoradapter = new SimpleCursorAdapter(DatabaseListView.this, R.layout.listcell, cursor, from, to);
database_results.setAdapter(cursoradapter);
database_results.getAdapter().notifyDataSetChanged();
Use the notifyDataSetChanged() method on the adapter like this:
final ArrayAdapter adapter = ((ArrayAdapter) getListAdapter());
runOnUiThread(new Runnable() {
public void run() {
adapter.notifyDataSetChanged();
}
});
Related
i want to run a search on a activity where a custom list is showing me the records of medicine. I haven't worked on SearchView.
My Medicine Database Code :
package com.example.sarhanaashir.wecare.Database_MedInfo;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.ArrayList;
public class DatabaseHelperMed extends SQLiteOpenHelper
{
private static final String Database_Name = "WeCareDatabaseMed";
private static final int Database_Ver = 1;
public DatabaseHelperMed(Context context, String name, SQLiteDatabase.CursorFactory factory, int version)
{
super(context,Database_Name,null,Database_Ver);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase)
{
String query = "CREATE TABLE tbl_med(id INTEGER PRIMARY KEY AUTOINCREMENT,MedName TEXT,MedSymptom TEXT)";
sqLiteDatabase.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1)
{
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS tbl_med");
this.onCreate(sqLiteDatabase);
}
public boolean addNewMedicine(MedicineRecord med_rec)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("MedName", med_rec.getMed_name() );
values.put("MedSymptom", med_rec.getMed_sym() );
db.insert("tbl_med", null, values);
db.close();
return true;
}
public ArrayList<MedicineRecord> getAllMed()
{
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<MedicineRecord> medi = new ArrayList<>();
Cursor cursor = db.rawQuery("select * from tbl_med", null);
if (cursor.moveToFirst())
{
while (!cursor.isAfterLast())
{
String id = cursor.getString(0);
String name = cursor.getString(1);
String sympt = cursor.getString(2);
medi.add(new MedicineRecord(name,sympt));
cursor.moveToNext();
}
}
return medi;
}
public Cursor searchTasks(SQLiteDatabase db, String searchTxt)
{
Cursor cursor;
String q = "select * tbl_med from where MedSymptom Like '"+searchTxt+"%'";
cursor = db.rawQuery(q,null);
return cursor;
}
}
My Activity Where SearchView is :
package com.example.sarhanaashir.wecare.Database_MedInfo;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.app.SearchManager;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;
import com.example.sarhanaashir.wecare.R;
import java.util.ArrayList;
public class Med_info extends AppCompatActivity {
private ArrayList<MedicineRecord> med_record;
private MedicineListAdapter adapter;
private ListView listView;
DatabaseHelperMed db;
SearchView searchView1;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_med_info);
inti();
searchView1 = (SearchView) findViewById(R.id.SVscrhMed);
searchView1.setOnQueryTextListener(new OnQueryTextListener()
{
#Override
public boolean onQueryTextSubmit(String qry)
{
return false;
}
#Override
public boolean onQueryTextChange(String newText)
{
return true;
}
});
}
private void inti()
{
db = new DatabaseHelperMed(Med_info.this,"WeCareDatabaseMed.db",null,1);
med_record = new ArrayList<>();
listView = (ListView) findViewById(R.id.Med_list);
adapter = new MedicineListAdapter(this, R.layout.med_rec_style, med_record);
listView.setAdapter(adapter);
fillmed();
}
private void fillmed()
{
med_record.clear();
med_record.addAll(db.getAllMed()); // Getting Medicine from database.
adapter.notifyDataSetChanged();
}
}
My Medicine Records are perfectly showing in my Custom List, the only thing i want is to put a searchView so that user can search the medicine from the list.
Try this code:
searchView1.setOnQueryTextListener(new OnQueryTextListener()
{
#Override
public boolean onQueryTextSubmit(String qry)
{
return false;
}
#Override
public boolean onQueryTextChange(String newText)
{
adapter.getFilter().filter(newText);
return true;
}
});
Try this code:
// DatabaseHelperMed //
final ArrayList<MedicineRecord> medicalRecords = new ArrayList<MedicineRecord>();
public ArrayList<MedicineRecord> getMedicine(String name) {
try {
medicalRecords.clear();
String selectQuery = "SELECT * FROM tbl_med "+" WHERE MedSymptom LIKE '%" + name + "%'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
MedicineRecord medRec = new MedicineRecord();
medRec.setMed_name(cursor.getString(1));
medRec.setMed_sym(cursor.getString(2));
medicalRecords.add(medRec);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return medicalRecords;
} catch (Exception e) {
// TODO: handle exception
Log.e("get_all_contacts", "" + e);
}
return medicalRecords;
}
// SearchView
searchView1.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
DatabaseHelperMed db ;
db = new DatabaseHelperMed(getApplicationContext());
ArrayList<MedicineRecord> medRecords = db.getMedicine(newText);
for (int i = 0; i < medRecords.size(); i++) {
String name = medRecords.get(i).getMed_name();
String symp = medRecords.get(i).getMed_sym();
}
return false;
}
});
I've been going round in circles with this for days and I can't get my head around what's wrong.
With the following code, when you press the "yes" button to delete the item you touched, it shows everything and appears to do everything but the item is not removed from the list.
Activity class:
package com1032.em00224.knit;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class NoteActivity extends Activity {
private ListView list;
DatabaseHandler db;
int id_To_Update = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note);
db = new DatabaseHandler(this);
ArrayList array_list = db.getAllNotes();
ArrayAdapter arrayAdapter =
new ArrayAdapter(this,android.R.layout.simple_list_item_1, array_list);
//adding it to the list view.
list = (ListView)findViewById(R.id.listView1);
list.setAdapter(arrayAdapter);
list.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View arg1, final int position,
long arg3) {
// TODO Auto-generated method stub
AlertDialog.Builder adb = new AlertDialog.Builder(NoteActivity.this);
adb.setTitle("Delete Note?");
adb.setMessage(R.string.deleteNote);
adb.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
db.deleteNote(position + 1);
arrayAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Note Deleted", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), com1032.em00224.knit.NoteActivity.class);
startActivity(intent);
}
});
adb.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
adb.show();
}
});
}
And the Database helper:
package com1032.em00224.knit;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;
public class DatabaseHandler extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "NoteDatabase.db";
public static final String NOTES_TABLE_NAME = "notes";
public static final String NOTES_COLUMN_ID = "id";
public static final String NOTES_COLUMN_NOTE = "note";
public DatabaseHandler(Context context)
{
super(context, DATABASE_NAME , null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table notes " +
"(id integer primary key, note text)"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS notes");
onCreate(db);
}
public boolean insertNote (String note)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("note", note);
db.insert("notes", null, contentValues);
return true;
}
public Cursor getData(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from contacts where id="+id+"", null );
return res;
}
public int numberOfRows(){
SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db, NOTES_TABLE_NAME);
return numRows;
}
public boolean updateNote (Integer id, String note)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("note", note);
db.update("notes", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
return true;
}
public Integer deleteNote (Integer id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("notes",
"id = ? ",
new String[] { Integer.toString(id) });
}
public ArrayList getAllNotes()
{
ArrayList array_list = new ArrayList();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from notes", null );
res.moveToFirst();
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(NOTES_COLUMN_NOTE)));
res.moveToNext();
}
return array_list;
}
}
Everything else, such as adding a new item, works as it should.
Edit - It now deletes the one that is selected, but it doesn't always actually delete and there seems to be no pattern - I've added some system.out.printlns to get a clearer picture but it says that it is deleting the right one when it isn't.
In some Projects I faced the same Problem. So there are two possible Solutions. First, after removing Your data from database, also remove item from listview/Adapter and call notifyDataSetChanged:
db.deleteNote(position);
arrayAdapter.remove(arrayAdapter.getItem(itemToRemove));
arrayAdapter.notifyDataSetChanged();
So, my Problem was, that this sometimes doesn´t work, until now, I don´t know what I was doing wrong. Anyway, if this doesn´t work, refresh the whole data after deleting:
private void refreshData(){
ArrayList array_list = db.getAllNotes();
ArrayAdapter arrayAdapter =
new ArrayAdapter(this,android.R.layout.simple_list_item_1, array_list);
list.setAdapter(arrayAdapter);
list.invalidateViews();
}
So this should look somehting like this in Your onClick:
adb.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
db.deleteNote(position);
refreshData();
Toast.makeText(getApplicationContext(), "Note Deleted", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), com1032.em00224.knit.NoteActivity.class);
startActivity(intent);
}
});
This is just from scratch, I can´t test the code for now because I have no IDE here. So don´t forget to do some Workaround (like opening and closing database etc.).
I'm having have some trouble with my Database activity. I am unable to write to the database and view the database using the following code.
my Database activity:
package com.jacob.eindproject;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import java.sql.*;
import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;
public class Database extends SQLiteAssetHelper {
public static final String KEY_PRODUCT = "Product";
public static final String KEY_EENHEID = "Eenheid";
public static final String KEY_KCAL = "Kcal";
private static final String DATABASE_NAME = "Voedsel";
private static final String DATABASE_TABLE = "Voeding";
private static final int DATABASE_VERSION = 1;
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class DbHelper extends SQLiteAssetHelper{
public DbHelper(Context context) {
super(context, DATABASE_NAME, context.getExternalFilesDir(null).getAbsolutePath(), null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
}
#Override
public void onUpgrade(SQLiteDatabase Voedsel, int oldVersion, int newVersion) {
Voedsel.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(Voedsel);
}
public void close(Database database) {
// TODO Auto-generated method stub
}
public Database(Context c){
ourContext = c;
}
public Database open() throws SQLException{
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close() {
ourHelper.close();
}
public long createEntry(String product, String kcal, String eenheid) {
ContentValues cv = new ContentValues();
cv.put(KEY_PRODUCT, product);
cv.put(KEY_EENHEID, eenheid);
cv.put(KEY_KCAL, kcal);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
public String getData() {
// TODO Auto-generated method stub
String[] columns = new String[]{ KEY_PRODUCT, KEY_EENHEID, KEY_KCAL};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_PRODUCT);
int iName = c.getColumnIndex(KEY_EENHEID);
int iHotness = c.getColumnIndex(KEY_KCAL);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iRow) + " " + c.getString(iName) + " " + c.getString(iHotness) + "\n";
}
return result;
}
}
My SQLView activity:
package com.jacob.eindproject;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class SQLView extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sqlview);
TextView tv = (TextView) findViewById(R.id.tvSQLinfo);
Database info = new Database(this);
info.open();
String data = info.getData();
info.close();
tv.setText(data);
}
}
SQLite activity:
package com.jacob.eindproject;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.View.OnClickListener;
public class SQLite extends Activity implements View.OnClickListener {
Button sqlUpdate, sqlView;
EditText sqlVoeding, sqlKcal, sqlEenheid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sqllite);
sqlUpdate = (Button) findViewById(R.id.bSQLUpdate);
sqlVoeding = (EditText) findViewById(R.id.etSQLVoeding);
sqlEenheid = (EditText) findViewById(R.id.etSQLEenheid);
sqlKcal = (EditText) findViewById(R.id.etSQLKcal);
sqlView = (Button) findViewById(R.id.bSQLopenView);
sqlView.setOnClickListener((android.view.View.OnClickListener) this);
sqlUpdate.setOnClickListener((android.view.View.OnClickListener) this);
}
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.bSQLUpdate:
boolean didItWork = true;
try{
String voeding = sqlVoeding.getText().toString();
String Kcal = sqlKcal.getText().toString();
String eenheid = sqlEenheid.getText().toString();
Database entry = new Database(SQLite.this);
entry.open();
entry.createEntry(voeding, Kcal, eenheid);
entry.close();
}catch (Exception e ){
didItWork = false;
}finally{
if (didItWork){
Dialog d = new Dialog(this);
d.setTitle("Heak Yeay");
TextView tv = new TextView(this);
tv.setText("Succes");
d.setContentView(tv);
d.show();
}
}
break;
case R.id.bSQLopenView:
Intent i = new Intent(this, SQLView.class);
startActivity(i);
}
}
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
}
}
I am having my database file(Voedsel.rar), in assets/databases/Voedsel.rar.
To write to your database, try a method like this:
public void insertVoeding(String product, String eenheid, String kcal) {
ourDatabase.execSQL("INSERT INTO Voeding (Product, Eenheid, Kcal) VALUES (?, ?, ?)",
new String[] {product, eenheid, kcal});
}
The question marks are replaced by the values in the string array. Your column names cannot be inserted using the string array, because the execSQL method puts quotation marks around these values. The query will fail if you try.
There are two ways to read from a database (may even be two ways to write to it, too). I personally prefer using raw queries, like this one to get the entire database:
public Cursor getEntireDB() {
return ourDatabase.rawQuery("SELECT * FROM Voeding");
}
You can then use the cursor in a CursorAdapter to create a list.
i follow this tutorial http://vimaltuts.com/android-tutorial-for-beginners/android-sqlite-database-example just tell me how do i add one more field in this code to take images as input and display?
please help me
import android.app.Activity;
import android.app.AlertDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class AddEditCountry extends Activity {
private long rowID;
private EditText nameEt;
private EditText capEt;
private EditText codeEt;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.add_country);
nameEt = (EditText) findViewById(R.id.nameEdit);
capEt = (EditText) findViewById(R.id.capEdit);
codeEt = (EditText) findViewById(R.id.codeEdit);
Bundle extras = getIntent().getExtras();
if (extras != null)
{
rowID = extras.getLong("row_id");
nameEt.setText(extras.getString("name"));
capEt.setText(extras.getString("cap"));
codeEt.setText(extras.getString("code"));
}
Button saveButton =(Button) findViewById(R.id.saveBtn);
saveButton.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
if (nameEt.getText().length() != 0)
{
AsyncTask saveContactTask =
new AsyncTask()
{
#Override
protected Object doInBackground(Object... params)
{
saveContact();
return null;
}
#Override
protected void onPostExecute(Object result)
{
finish();
}
};
saveContactTask.execute((Object[]) null);
}
else
{
AlertDialog.Builder alert = new
AlertDialog.Builder(AddEditCountry.this);
alert.setTitle(R.string.errorTitle);
alert.setMessage(R.string.errorMessage);
alert.setPositiveButton(R.string.errorButton, null);
alert.show();
}
}
});
}
private void saveContact()
{
DatabaseConnector dbConnector = new DatabaseConnector(this);
if (getIntent().getExtras() == null)
{
dbConnector.insertContact(nameEt.getText().toString(),
capEt.getText().toString(),
codeEt.getText().toString());
}
else
{
dbConnector.updateContact(rowID,
nameEt.getText().toString(),
capEt.getText().toString(),
codeEt.getText().toString());
}
}
}
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.AdapterView.OnItemClickListener;
public class CountryList extends ListActivity {
public static final String ROW_ID = "row_id";
private ListView conListView;
private CursorAdapter conAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
conListView=getListView();
conListView.setOnItemClickListener(viewConListener);
// map each name to a TextView
String[] from = new String[] { "name" };
int[] to = new int[] { R.id.countryTextView };
conAdapter = new SimpleCursorAdapter(CountryList.this, R.layout.country_list,
null, from, to);
setListAdapter(conAdapter); // set adapter
}
#Override
protected void onResume()
{
super.onResume();
new GetContacts().execute((Object[]) null);
}
#Override
protected void onStop()
{
Cursor cursor = conAdapter.getCursor();
if (cursor != null)
cursor.deactivate();
conAdapter.changeCursor(null);
super.onStop();
}
private class GetContacts extends AsyncTask
{
DatabaseConnector dbConnector = new DatabaseConnector(CountryList.this);
#Override
protected Cursor doInBackground(Object... params)
{
dbConnector.open();
return dbConnector.getAllContacts();
}
#Override
protected void onPostExecute(Cursor result)
{
conAdapter.changeCursor(result); // set the adapter's Cursor
dbConnector.close();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.country_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
Intent addContact = new Intent(CountryList.this, AddEditCountry.class);
startActivity(addContact);
return super.onOptionsItemSelected(item);
}
OnItemClickListener viewConListener = new OnItemClickListener()
{
public void onItemClick(AdapterView arg0, View arg1, int arg2,long arg3)
{
Intent viewCon = new Intent(CountryList.this, ViewCountry.class);
viewCon.putExtra(ROW_ID, arg3);
startActivity(viewCon);
}
};
}
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;
public class ViewCountry extends Activity {
private long rowID;
private TextView nameTv;
private TextView capTv;
private TextView codeTv;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.view_country);
setUpViews();
Bundle extras = getIntent().getExtras();
rowID = extras.getLong(CountryList.ROW_ID);
}
private void setUpViews() {
nameTv = (TextView) findViewById(R.id.nameText);
capTv = (TextView) findViewById(R.id.capText);
codeTv = (TextView) findViewById(R.id.codeText);
}
#Override
protected void onResume()
{
super.onResume();
new LoadContacts().execute(rowID);
}
private class LoadContacts extends AsyncTask
{
DatabaseConnector dbConnector = new DatabaseConnector(ViewCountry.this);
#Override
protected Cursor doInBackground(Long... params)
{
dbConnector.open();
return dbConnector.getOneContact(params[0]);
}
#Override
protected void onPostExecute(Cursor result)
{
super.onPostExecute(result);
result.moveToFirst();
// get the column index for each data item
int nameIndex = result.getColumnIndex("name");
int capIndex = result.getColumnIndex("cap");
int codeIndex = result.getColumnIndex("code");
nameTv.setText(result.getString(nameIndex));
capTv.setText(result.getString(capIndex));
codeTv.setText(result.getString(codeIndex));
result.close();
dbConnector.close();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.view_country_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.editItem:
Intent addEditContact =
new Intent(this, AddEditCountry.class);
addEditContact.putExtra(CountryList.ROW_ID, rowID);
addEditContact.putExtra("name", nameTv.getText());
addEditContact.putExtra("cap", capTv.getText());
addEditContact.putExtra("code", codeTv.getText());
startActivity(addEditContact);
return true;
case R.id.deleteItem:
deleteContact();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void deleteContact()
{
AlertDialog.Builder alert = new AlertDialog.Builder(ViewCountry.this);
alert.setTitle(R.string.confirmTitle);
alert.setMessage(R.string.confirmMessage);
alert.setPositiveButton(R.string.delete_btn,
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int button)
{
final DatabaseConnector dbConnector =
new DatabaseConnector(ViewCountry.this);
AsyncTask deleteTask =
new AsyncTask()
{
#Override
protected Object doInBackground(Long... params)
{
dbConnector.deleteContact(params[0]);
return null;
}
#Override
protected void onPostExecute(Object result)
{
finish();
}
};
deleteTask.execute(new Long[] { rowID });
}
}
);
alert.setNegativeButton(R.string.cancel_btn, null).show();
}
}
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class DatabaseConnector {
private static final String DB_NAME = "WorldCountries";
private SQLiteDatabase database;
private DatabaseOpenHelper dbOpenHelper;
public DatabaseConnector(Context context) {
dbOpenHelper = new DatabaseOpenHelper(context, DB_NAME, null, 1);
}
public void open() throws SQLException
{
//open database in reading/writing mode
database = dbOpenHelper.getWritableDatabase();
}
public void close()
{
if (database != null)
database.close();
}
public void insertContact(String name, String cap, String code)
{
ContentValues newCon = new ContentValues();
newCon.put("name", name);
newCon.put("cap", cap);
newCon.put("code", code);
open();
database.insert("country", null, newCon);
close();
}
public void updateContact(long id, String name, String
cap,String code)
{
ContentValues editCon = new ContentValues();
editCon.put("name", name);
editCon.put("cap", cap);
editCon.put("code", code);
open();
database.update("country", editCon, "_id=" + id, null);
close();
}
public Cursor getAllContacts()
{
return database.query("country", new String[] {"_id",
"name"},
null, null, null, null, "name");
}
public Cursor getOneContact(long id)
{
return database.query("country", null, "_id=" + id, null,
null, null, null);
}
public void deleteContact(long id)
{
open();
database.delete("country", "_id=" + id, null);
close();
}
}
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseOpenHelper extends SQLiteOpenHelper {
public DatabaseOpenHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createQuery = "CREATE TABLE country (_id integer primary key
autoincrement,name, cap, code);";
db.execSQL(createQuery);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
You can easily add field of BLOB type in sql, and put images like set of bytes:
//while writing to db:
ByteArrayOutputStream outStr = new ByteArrayOutputStream();
image.compress(CompressFormat.PNG, 100, outStr);
byte[] blob = outStr.toByteArray();
contentValues.put("image", blob);
//while reading from cursor:
byte[] blob = cursor.getBlob("image");
Bitmap image = BitmapFactory.decodeByteArray(blob, 0, blob.length);
I want to make it so that there is a ListView with a Button above it. The users clicks that button, and it opens a dialog with an EditText and an OK and Cancel button. When the user clicks OK, whatever text is entered into the EditText gets put into the SQLiteDatabase, which is reflected in the ListView.
I've already set up my SQLiteDatabase and have set an adapter for the List to show the SQLiteDatabase, but I need to figure out how to use the edittext.getText().toString() method to add to the SQLiteDatabase. I will need a code example.
If you need it, here's my main .java:
package com.gantt.shoppinglist;
import android.app.Dialog;
import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class ShoppingList extends ListActivity {
/** Called when the activity is first created. */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final DataHelper dataHelper = new DataHelper(this);
ListView lv = (ListView) findViewById(android.R.id.list);
SimpleCursorAdapter adapter = null;
final SQLiteDatabase db = dataHelper.selectAll();
Cursor c = db.rawQuery("SELECT DISTINCT oid as _id,name FROM table1 ORDER BY name", null);
if (c.moveToFirst()) {
String[] columnNames = new String[]{"name"};
int[] list = new int[]{android.R.id.list};
adapter = new SimpleCursorAdapter(this, R.layout.rowlayout, c, columnNames, list);
}
lv.setAdapter(adapter);
Button button1main = (Button) findViewById(R.id.add);
button1main.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final Dialog additem = new Dialog(ShoppingList.this);
additem.setContentView(R.layout.maindialog);
final EditText et = (EditText)additem.findViewById(R.id.edittext);
additem.setTitle("Type your item");
additem.setCancelable(true);
et.setHint("Type the name of an item...");
Button button = (Button) additem.findViewById(R.id.cancel);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
additem.dismiss();
}
});
additem.show();
Button ok = (Button) additem.findViewById(R.id.ok);
ok.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
et.getText().toString();
additem.dismiss();
et.setText("");
}
});
}
});
}
}
Here is my DataHelper class:
package com.gantt.shoppinglist;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;
public class DataHelper {
public static final String DATABASE_NAME = "items.db";
public static final int DATABASE_VERSION = 1;
public static final String TABLE_NAME = "table1";
public static final String KEY_ROWID = "_id";
private Context context;
private SQLiteDatabase db;
private SQLiteStatement insertStmt;
private static final String INSERT = "insert into "
+ TABLE_NAME + "(name) values (?)";
public DataHelper(Context context) {
this.context = context;
OpenHelper openHelper = new OpenHelper(this.context);
this.db = openHelper.getWritableDatabase();
this.insertStmt = this.db.compileStatement(INSERT);
}
public long insert(String name) {
this.insertStmt.bindString(1, name);
return this.insertStmt.executeInsert();
}
public void deleteAll() {
this.db.delete(TABLE_NAME, null, null);
}
public SQLiteDatabase selectAll() {
List<String> list = new ArrayList<String>();
Cursor cursor = this.db.query(TABLE_NAME, new String[] { "name" },
null, null, null, null, "name desc");
if (cursor.moveToFirst()) {
do {
list.add(cursor.getString(0));
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return db;
}
public static String getDatabaseName() {
return DATABASE_NAME;
}
private static class OpenHelper extends SQLiteOpenHelper {
OpenHelper(Context context) {
super(context, getDatabaseName(), null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + "(id INTEGER PRIMARY KEY, name TEXT");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w("Example", "Upgrading database, this will drop tables and recreate.");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
}
Using the current methods you have, and assuming that you understand the code that you used for the database adapter, just do this:
String item = et.getText().toString();// these two lines are the
dataHelper.insert(item); // only change you have to do
additem.dismiss();
et.setText("");
After doing this, you have to call the notifyDataSetChanged method of your SimpleCursorAdapter object.
A simple sample method for your DataHelper class:
public long createUser(String email, String password, String fullName) {
ContentValues initialValues = new ContentValues();
initialValues.put("email", email);
initialValues.put("password", password);
initialValues.put("fullName", fullName);
return mDb.insert(TABLE_NAME, null, initialValues);
}