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);
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 have this custom Loader that is supposed to insert some dummy data I sent to it in a database using content resolver. I'm using the getLoaderManager().initLoader(INSERT_DUMMY_DATA_ID, null, this);
in the activity. The constructor gets called. But the onStartLoading() and loadinBackgroung() arent called.
Here is the ProductInsertionLoader.java
public class ProductInsertionLoader extends AsyncTaskLoader {
private String LOG_TAG = ProductInsertionLoader.class.getSimpleName();
private ArrayList<ContentValues> mValues;
private ContentResolver mContentResolver;
public ProductInsertionLoader(Context context, ContentResolver contentResolver, ArrayList<ContentValues> values) {
super(context);
mValues = values;
mContentResolver = contentResolver;
Log.v(LOG_TAG, "constructor called");
}
#Override
public Object loadInBackground() {
Log.v(LOG_TAG, "loadInBackground() called");
ArrayList<Uri> uris = new ArrayList<>();
for (ContentValues value : mValues) {
Uri uri = mContentResolver.insert(ProductContract.ProductEntry.CONTENT_URI, value);
Log.v(LOG_TAG, "Dummy data inserted. ID: " + ContentUris.parseId(uri));
uris.add(uri);
}
return null;
}
#Override
protected void onStartLoading() {
Log.v(LOG_TAG, "onStartLoading() called");
forceLoad();
}
}
Here is how I'm calling it in the CatalogActivity.java
package com.example.android.inventory;
import android.app.LoaderManager;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.CursorLoader;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.android.inventory.data.ProductContract.ProductEntry;
import com.example.android.inventory.data.ProductInsertionLoader;
import java.io.IOException;
import java.util.ArrayList;
public class CatalogActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> {
private static final String LOG_TAG = CatalogActivity.class.getSimpleName();
private ProductCursorAdapter mCursorAdapter;
private static final int URL_LOADER = 0;
private static final int INSERT_DUMMY_DATA_ID = 1;
private Uri mCurrentProductUri;
private ArrayList<ContentValues> mValues;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_catalog);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(CatalogActivity.this, EditorActivity.class);
startActivity(intent);
}
});
final ListView listView = (ListView) findViewById(R.id.list_view_product);
TextView textView = (TextView) findViewById(R.id.empty_view);
listView.setEmptyView(textView);
mCursorAdapter = new ProductCursorAdapter(this, null, getContentResolver());
listView.setAdapter(mCursorAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(CatalogActivity.this, EditorActivity.class);
Uri currentProductUri = ContentUris.withAppendedId(ProductEntry.CONTENT_URI, id);
intent.setData(currentProductUri);
startActivity(intent);
}
});
getLoaderManager().initLoader(URL_LOADER, null, CatalogActivity.this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_catalog, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_insert_dummy_data:
insertDummyData();
return true;
case R.id.action_delete_all_entries:
showDeleteConfirmationDialog("Delete all products?", null);
return true;
}
return super.onOptionsItemSelected(item);
}
private void insertDummyData() {
mValues = new ArrayList<>();
mValues.add(getContentValues("Sugar", 50, 60, "Sweet Sugar Company", R.drawable.sugar));
mValues.add(getContentValues("Salt", 20, 30, "Salty Salt Company", R.drawable.salt));
mValues.add(getContentValues("Bread", 45, 20, "Nanglo", R.drawable.bread));
mValues.add(getContentValues("Biscuit", 75, 20, "GoodDay", R.drawable.biscuit));
mValues.add(getContentValues("Noodles", 15, 200, "CupMen", R.drawable.noodles));
mValues.add(getContentValues("Milk", 33, 100, "DDC", R.drawable.milk));
mValues.add(getContentValues("Cheese", 80, 30, "Amul", R.drawable.cheese));
getLoaderManager().initLoader(INSERT_DUMMY_DATA_ID, null, this).forceLoad();
Toast.makeText(this, "Dummy Data Inserted", Toast.LENGTH_SHORT).show();
}
private ContentValues getContentValues(String name, int price, int quantity, String supplier, int resId) {
ContentValues values = new ContentValues();
values.put(ProductEntry.COLUMN_NAME, name);
values.put(ProductEntry.COLUMN_PRICE, price);
values.put(ProductEntry.COLUMN_QUANTITY, quantity);
values.put(ProductEntry.COLUMN_SUPPLIER, supplier);
//Uri for the sugar drawable
Uri imageUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE +
"://" + getResources().getResourcePackageName(resId)
+ '/' + getResources().getResourceTypeName(resId)
+ '/' + getResources().getResourceEntryName(resId));
Bitmap bitmap = null;
//Converting the sugar image into a thumbnail
try {
bitmap = DbBitmapUtility.getThumbnail(imageUri, this);
} catch (IOException e) {
e.printStackTrace();
}
//Converting the sugar thumbnail into a byte array.
byte[] image = DbBitmapUtility.getBitmapAsByteArray(bitmap);
values.put(ProductEntry.COLUMN_IMAGE, image);
return values;
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
switch (id) {
case URL_LOADER:
String[] projection = {
ProductEntry._ID,
ProductEntry.COLUMN_NAME,
ProductEntry.COLUMN_QUANTITY,
ProductEntry.COLUMN_PRICE,
ProductEntry.COLUMN_SUPPLIER,
ProductEntry.COLUMN_IMAGE
};
return new CursorLoader(
this,
ProductEntry.CONTENT_URI,
projection,
null,
null,
null);
case INSERT_DUMMY_DATA_ID:
new ProductInsertionLoader(this, getContentResolver(), mValues);
return null;
default:
Log.v(LOG_TAG, "onCreateLoader: Invalid id");
return null;
}
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if (loader.getId() == URL_LOADER) {
mCursorAdapter.swapCursor(data);
} else return;
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
mCursorAdapter.swapCursor(null);
}
}
As you can see I'm using two loaders. One CursorLoader to load all the database data into the UI, and a second custom AsyncTaskLoader to insert some dummy data on to the database on a background thread.
Why isn't the custom loader's onStartLoading() or loadInBackground() not being called?
hi, guys! I would like a help. How to sorting my entries in a ListView Activity from sql db by word, instead of id_key? This is a personal dictionary app
I'm a newbie.
DictionaryDataHelper
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class DictionaryDatabaseHelper extends SQLiteOpenHelper {
final static String DICTIONARY_DATABASE="dictionary";
final static String ITEM_ID_COLUMN="id";
final static String WORD_COLUMN="word";
final static String DEFINITION_COLUMN="definition";
final static String CREATE_DATABASE_QUERY="CREATE TABLE "+DICTIONARY_DATABASE+" ( "+
ITEM_ID_COLUMN+" INTEGER PRIMARY KEY AUTOINCREMENT, "+
WORD_COLUMN+" TEXT , "+
DEFINITION_COLUMN+" TEXT)";
final static String ON_UPGRADE_QUERY="DROP TABLE "+DICTIONARY_DATABASE;
Context context;
public DictionaryDatabaseHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, DICTIONARY_DATABASE, factory, version);
this.context=context;
}
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(CREATE_DATABASE_QUERY);
}
#Override
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
database.execSQL(ON_UPGRADE_QUERY);
onCreate(database);
}
public long insertData(WordDefinition wordDefinition) {
SQLiteDatabase database=this.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(WORD_COLUMN, wordDefinition.word);
values.put(DEFINITION_COLUMN, wordDefinition.definition);
return database.insert(DICTIONARY_DATABASE, null, values);
}
public long updateData(WordDefinition wordDefinition) {
SQLiteDatabase database=this.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(WORD_COLUMN, wordDefinition.word);
values.put(DEFINITION_COLUMN, wordDefinition.definition);
return database.update(DICTIONARY_DATABASE, values, WORD_COLUMN+" =?", new String[]{wordDefinition.word});
}
public void deleteData(WordDefinition wordDefinition) {
SQLiteDatabase database=this.getWritableDatabase();
String queryString="DELETE FROM "+DICTIONARY_DATABASE+" WHERE "+WORD_COLUMN+" = '"+wordDefinition.word+"'";
database.execSQL(queryString);
}
public ArrayList<WordDefinition> getAllWords() {
ArrayList<WordDefinition> arrayList=new ArrayList<WordDefinition>();
SQLiteDatabase database=this.getReadableDatabase();
String selectAllQueryString="SELECT * FROM "+DICTIONARY_DATABASE;
Cursor cursor=database.rawQuery(selectAllQueryString, null);
if (cursor.moveToFirst()) {
do {
WordDefinition wordDefinition=new WordDefinition(cursor.getString(cursor.getColumnIndex(WORD_COLUMN)), cursor.getString(cursor.getColumnIndex(DEFINITION_COLUMN)));
arrayList.add(wordDefinition);
} while (cursor.moveToNext());
}
return arrayList;
}
public WordDefinition getWordDefinition(String word) {
SQLiteDatabase database=this.getReadableDatabase();
WordDefinition wordDefinition=null;
String selectQueryString="SELECT * FROM "+DICTIONARY_DATABASE+ " WHERE "+WORD_COLUMN+" = '"+word+ "'";
Cursor cursor=database.rawQuery(selectQueryString, null);
if (cursor.moveToFirst()) {
wordDefinition=new WordDefinition(cursor.getString(cursor.getColumnIndex(WORD_COLUMN)), cursor.getString(cursor.getColumnIndex(DEFINITION_COLUMN)));
}
return wordDefinition;
}
public WordDefinition getWordDefinition(long id) {
SQLiteDatabase database=this.getReadableDatabase();
WordDefinition wordDefinition=null;
String selectQueryString="SELECT * FROM "+DICTIONARY_DATABASE+ " WHERE "+ITEM_ID_COLUMN+" = '"+id+ "'";
Cursor cursor=database.rawQuery(selectQueryString, null);
if (cursor.moveToFirst()) {
wordDefinition=new WordDefinition(cursor.getString(cursor.getColumnIndex(WORD_COLUMN)), cursor.getString(cursor.getColumnIndex(DEFINITION_COLUMN)));
}
return wordDefinition;
}
public void initializeDatabaseFortheFirstTime(ArrayList<WordDefinition> wordDefinitions) {
SQLiteDatabase database=this.getWritableDatabase();
database.execSQL("BEGIN");
ContentValues contentValues=new ContentValues();
for (WordDefinition wordDefinition : wordDefinitions) {
contentValues.put(WORD_COLUMN, wordDefinition.word);
contentValues.put(DEFINITION_COLUMN, wordDefinition.definition);
database.insert(DICTIONARY_DATABASE, null, contentValues);
}
database.execSQL("COMMIT");
}
}
DictionaryListActivity
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class DictionaryListActivity extends Activity {
TextView userTextView;
EditText searchEditText;
Button searchButton;
ListView dictionaryListView;
String logTagString="DICTIONARY";
ArrayList<WordDefinition> allWordDefinitions=new ArrayList<WordDefinition>();
DictionaryDatabaseHelper myDictionaryDatabaseHelper;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dictionary_list);
Log.d("DICTIONARY", "second activity started");
userTextView=(TextView) findViewById(R.id.personTextView);
userTextView.setText(getIntent().getStringExtra(MainActivity.USER_NAME_STRING));
searchEditText=(EditText) findViewById(R.id.searchEditText);
searchButton=(Button) findViewById(R.id.searchButton);
dictionaryListView=(ListView) findViewById(R.id.dictionaryListView);
myDictionaryDatabaseHelper=new DictionaryDatabaseHelper(this, "Dictionary", null, 1);
sharedPreferences=getSharedPreferences(MainActivity.SHARED_NAME_STRING, MODE_PRIVATE);
boolean initialized=sharedPreferences.getBoolean("initialized", false);
if (initialized==false) {
//Log.d(logTagString, "initializing for the first time");
initializeDatabase();
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putBoolean("initialized", true);
editor.commit();
}else {
Log.d(logTagString, "db already initialized");
}
allWordDefinitions=myDictionaryDatabaseHelper.getAllWords();
dictionaryListView.setAdapter(new BaseAdapter() {
#Override
public View getView(int position, View view, ViewGroup arg2) {
if (view==null) {
view=getLayoutInflater().inflate(R.layout.list_item, null);
}
TextView textView=(TextView) view.findViewById(R.id.listItemTextView);
textView.setText(allWordDefinitions.get(position).word);
return view;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return allWordDefinitions.size();
}
});
dictionaryListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long arg3) {
Intent intent =new Intent(DictionaryListActivity.this, WordDefinitionDetailActivity.class);
intent.putExtra("word", allWordDefinitions.get(position).word);
intent.putExtra("definition", allWordDefinitions.get(position).definition);
startActivity(intent);
}
});
searchButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String string=searchEditText.getText().toString();
WordDefinition wordDefinition=myDictionaryDatabaseHelper.getWordDefinition(string);
if (wordDefinition==null) {
Toast.makeText(DictionaryListActivity.this, "Expressão não encontrada.", Toast.LENGTH_LONG).show();
}else {
Intent intent =new Intent(DictionaryListActivity.this, WordDefinitionDetailActivity.class);
intent.putExtra("word", wordDefinition.word);
intent.putExtra("definition", wordDefinition.definition);
startActivity(intent);
}
}
});
}
//
private void initializeDatabase() {
InputStream inputStream=getResources().openRawResource(R.raw.dictionary);
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
DictionaryLoader.loadData(bufferedReader, myDictionaryDatabaseHelper);
}
}
DictionaryLoader
package com.ecidioms;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class DictionaryLoader implements Comparator<WordDefinition> {
#Override
public int compare(WordDefinition A, WordDefinition B) {
return A.compareTo(B);
}
public static void loadData(BufferedReader bufferedReader, DictionaryDatabaseHelper dictionaryDatabaseHelper) {
ArrayList<WordDefinition> allWords=new ArrayList<WordDefinition>();
Collections.sort(allWords, new DictionaryLoader());
try {
BufferedReader fileReader=bufferedReader;
try {
int c=17;
c=fileReader.read();
while (c!=(-1)) {
StringBuilder stringBuilder=new StringBuilder();
while ((char)c!='\n'&&c!=-1) {
try {
stringBuilder.append((char)c);
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println(stringBuilder.length());
//e.printStackTrace();
}
c= fileReader.read();
if (c==-1) {
return;
}
}
String wordString=stringBuilder.toString();
ArrayList<String> definition=new ArrayList<String>();
while (c=='\n'||c=='\t') {
c= fileReader.read();
if (c=='\n'||c=='\t'||c=='\r') {
StringBuilder stringBuilder2=new StringBuilder();
while (c!='\n') {
stringBuilder2.append((char)c);
c=fileReader.read();
}
String definitionString=stringBuilder2.toString();
definition.add(definitionString);
}else {
break;
}
}
wordString=wordString.trim();
//Logger.log("word Loaded: "+(++counter)+" :"+wordString);
allWords.add(new WordDefinition(wordString, definition));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
dictionaryDatabaseHelper.initializeDatabaseFortheFirstTime(allWords);
fileReader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
WordDefinition
import java.util.ArrayList;
public class WordDefinition {
String word,definition;
public WordDefinition(String word,ArrayList<String> alldefinition) {
this.word=word;
StringBuilder stringBuilder=new StringBuilder();
for (String string : alldefinition) {
stringBuilder.append(string);
}
this.definition=stringBuilder.toString();
}
public WordDefinition(String word,String alldefinition) {
this.word=word;
this.definition=alldefinition;
}
}
WordDefinitionDetailActivity
import com.ecidioms.R;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class WordDefinitionDetailActivity extends Activity {
TextView wordTextView;
TextView definitionTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_word_definition_detail);
wordTextView=(TextView) findViewById(R.id.wordTextView);
definitionTextView=(TextView) findViewById(R.id.definitionTextView);
Log.d("DICTIONARY", "third activity started");
wordTextView.setText(getIntent().getStringExtra("word"));
definitionTextView.setText(getIntent().getStringExtra("definition"));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.word_definition_detail, menu);
return true;
}
}
The easiest way to sort all your WordDefinitions would be to create a Custom Comparator like this:
class DefinitionComparator implements Comparator<WordDefinition> {
#Override
public int compareTo(WordDefinition this, WordDefinition that) {
return this.getWord().compareTo(that.getWord());
}
}
And then pass a new instance of your custom comparator to a the Collections.sort method with your returned ArrayList(from the database) like this:
Collections.sort(myWordDefinitionList, this);
EDIT:
So you need to add word and definition getters in your WordDefinition class:
public String getWord() {
return this.word;
}
public String getDefinition() {
return this.definition;
}
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();
}
});
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
how to save image in sqllite database?
I follow this tutorial and I just want to add 1 new field in this code to browse and upload an image.
How can I do this please?
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
public class AddEditCountry extends Activity {
private long rowID;
private EditText nameEt;
private EditText capEt;
private EditText codeEt;
private EditText Donedate;
private EditText Notes;
private EditText Person;
private ImageView imageView1;
Bitmap yourSelectedImage;
String img;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.add_country);
nameEt = (EditText) findViewById(R.id.Address);
capEt = (EditText) findViewById(R.id.Stage);
codeEt = (EditText) findViewById(R.id.Dueby);
Donedate = (EditText) findViewById(R.id.Donedate);
Notes = (EditText) findViewById(R.id.Notes);
Person = (EditText) findViewById(R.id.Person);
imageView1 = (ImageView) findViewById(R.id.imageView1);
Button Browse = (Button) findViewById(R.id.Browse);
Browse.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 0);
}
});
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"));
Donedate.setText(extras.getString("Location"));
Notes.setText(extras.getString("Notes"));
Person.setText(extras.getString("Person"));
img=extras.getString("image");
imageView1.setImageBitmap(yourSelectedImage);
}
Button saveButton =(Button) findViewById(R.id.saveBtn);
saveButton.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
if (nameEt.getText().length() != 0)
{
AsyncTask<Object, Object, Object> saveContactTask =
new AsyncTask<Object, Object, Object>()
{
#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()
{
ByteArrayOutputStream stream = new ByteArrayOutputStream();
yourSelectedImage.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] imageInByte = stream.toByteArray();
DatabaseConnector dbConnector = new DatabaseConnector(this);
if (getIntent().getExtras() == null)
{
dbConnector.insertContact(nameEt.getText().toString(),
capEt.getText().toString(),
codeEt.getText().toString(),
Donedate.getText().toString(),
Notes.getText().toString(),
Person.getText().toString(),
imageInByte.toString()
);
}
else
{
dbConnector.updateContact(rowID,
nameEt.getText().toString(),
capEt.getText().toString(),
codeEt.getText().toString(),
Donedate.getText().toString(),
Notes.getText().toString(),
Person.getText().toString(), null
);
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent
imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case 0:
if(resultCode == RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn,
null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex); // file path of selected
image
cursor.close();
// Convert file path into bitmap image using below line.
yourSelectedImage = BitmapFactory.decodeFile(filePath);
// put bitmapimage in your imageview
imageView1.setImageBitmap(yourSelectedImage);
}
}
}
}
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, String
LocationEd, String Notes, String Person,byte[] image)
{
ContentValues newCon = new ContentValues();
newCon.put("name", name);
newCon.put("cap", cap);
newCon.put("code", code);
newCon.put("Location",LocationEd);
newCon.put("Notes",Notes);
newCon.put("Person",Person);
newCon.put("Image", image);
open();
database.insert("country", null, newCon);
close();
}
public void updateContact(long id, String name, String
cap,String code,String LocationEd, String Notes, String Person ,byte[] image)
{
ContentValues editCon = new ContentValues();
editCon.put("name", name);
editCon.put("cap", cap);
editCon.put("code", code);
editCon.put("Location", LocationEd);
editCon.put("Notes", Notes);
editCon.put("Person", Person);
editCon.put("Image", image);
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 text,cap text,code text,Location double,Notes text,Person
text,Image Blob);";
db.execSQL(createQuery);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
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
p ublic 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<Object, Object, Cursor>
{
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.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class ViewCountry extends Activity {
private long rowID;
private TextView nameTv;
private TextView capTv;
private TextView codeTv;
private TextView Locationlb;
private TextView Noteslb;
private TextView Personlb;
byte[] byteImage2 = null;
private ImageView imageView2;
#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);
Locationlb = (TextView) findViewById(R.id.Location_lbl);
Noteslb = (TextView) findViewById(R.id.Notes_lbl);
Personlb = (TextView) findViewById(R.id.Person_lbl);
imageView2= (ImageView) findViewById(R.id.imageView2);
Button Browse2 = (Button) findViewById(R.id.Browse2);
Browse2.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 0);
}
});
}
#Override
protected void onResume()
{
super.onResume();
new LoadContacts().execute(rowID);
}
private class LoadContacts extends AsyncTask<Long, Object, Cursor>
{
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");
int LocationIndex = result.getColumnIndex("Location");
int NotesIndex = result.getColumnIndex("Notes");
int PersonIndex = result.getColumnIndex("Person");
byteImage2=result.getBlob(result.getColumnIndex("Image"));
nameTv.setText(result.getString(nameIndex));
capTv.setText(result.getString(capIndex));
codeTv.setText(result.getString(codeIndex));
Locationlb.setText(result.getString(LocationIndex));
Noteslb.setText(result.getString(NotesIndex));
Personlb.setText(result.getString(PersonIndex));
imageView2.setImageURI(byteImage2);
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());
addEditContact.putExtra("Location", Locationlb.getText());
addEditContact.putExtra("Notes", Noteslb.getText());
addEditContact.putExtra("Person", Personlb.getText());
addEditContact.putExtra("Image", (CharSequence)
imageView2.getDrawable());
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<Long, Object, Object> deleteTask =
new AsyncTask<Long, Object, Object>()
{
#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();
}
}
1.Image first converted into base64 and then store this string into database
This link will be help you
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),
R.drawable.a1);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte [] ba = bao.toByteArray();
String ba1=Base64.encodeBytes(ba);
and when you want to get image and setbackground image use
Bitmap bitmap = BitmapFactory.decodeByteArray(image, 0,image.length);
imag_view.setImageBitmap(bitmap);