I am not able to set multiple image in grid view? - android

I am creating app in which
1.take photo from camera.
2.save its URI in database
3.using cursor and adaptor i retrieve image uri and sets in grid view.
i am getting error as " error opening trace file: No such file or directory (2)"
also i cant see any folder formed with name "my image"
Main activity
public class MainActivity extends ActionBarActivity {
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
final int MEDIA_TYPE_IMAGE=2;
Button click;
ImageView image;
Uri fileuri;
int camera_capture=100;
GridView gridactivity;
Gridsource source;
customiseadapter adapter;
ArrayList<String> List;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
source=new Gridsource(this);
source.open();
gridactivity=(GridView) findViewById(R.id.grid_view);
List=source.getallpath();
adapter=new customiseadapter(getApplicationContext(),List);
gridactivity.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.Add_button) {
captureimage();
}
return super.onOptionsItemSelected(item);
}
private void captureimage() {
if(cameraavail())
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileuri = getmediafileuri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT , fileuri);
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
else
{
Toast.makeText(getApplicationContext(), "device with not camera support", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int resultrequest, int resultcode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(resultrequest, resultcode, data);
if (resultrequest==CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultcode==RESULT_OK) {
source.createpicture(fileuri.toString());
ArrayList<String> list1 = source.getallpath();
customiseadapter adapter1= new customiseadapter(getApplicationContext(), list1);
gridactivity.setAdapter(adapter1);
}else if
(resultcode==RESULT_CANCELED)
{
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
}
}
}
private Uri getmediafileuri(int arg) {
File mediafile= getmediafile(arg);
return Uri.fromFile(mediafile) ;
}
private File getmediafile(int type){
File mediadir=new File(Environment.getExternalStorageDirectory()+"/myimages");
if(!mediadir.exists())
{
mediadir.mkdir();
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediafile;
if(type==MEDIA_TYPE_IMAGE )
{
mediafile= new File(mediadir.getPath() + File.separator + "img_" + timeStamp +".png" );
}else
{
return null;
}
return mediafile;
}
private boolean cameraavail() {
if(getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA))
return true;
else
return false;
}
}
2.Mysqlitehelper
public class Mysqlitehelper extends SQLiteOpenHelper {
public static final String Table_grid ="gridtable";
public static final String column_ID ="ID";
public static final String column_URI ="URI";
public static final String DB_name = "Griddb";
public static final int version =1;
public static final String Database_create = "create table "+Table_grid+ " ("
+ column_ID +" integer primary key autoincrement,"
+ column_URI + " text not null);";
public Mysqlitehelper(Context context) {
super(context, DB_name, null, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(Database_create);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS"+ Table_grid);
onCreate(db);
}
}
3.customiseadapter
public class customiseadapter extends BaseAdapter {
Context context;
ArrayList<String> list;
public customiseadapter(Context context, ArrayList<String> list) {
super();
this.context = context;
this.list = list;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return list.get(arg0);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
ImageView image = new ImageView(context);
Uri uri = Uri.parse(list.get(arg0));
image.setImageURI(uri);
image.setScaleType(ImageView.ScaleType.CENTER_CROP);
image.setLayoutParams(new GridView.LayoutParams(70, 70));
return image;
}
}
Gridsource
public class Gridsource {
Mysqlitehelper mydbhelper;
SQLiteDatabase database;
String[] column_name={Mysqlitehelper.column_ID,Mysqlitehelper.column_URI};
public Gridsource(Context context) {
mydbhelper= new Mysqlitehelper(context);
}
public void open()
{
database=mydbhelper.getWritableDatabase();
}
public void close()
{
mydbhelper.close();
}
public void createpicture(String path)
{
ContentValues value= new ContentValues();
value.put(Mysqlitehelper.column_URI, path);
database.insert(Mysqlitehelper.Table_grid, null, value);
}
public ArrayList<String>getallpath()
{
ArrayList<String> pathlist = new ArrayList<String>();
Cursor cursor = database.query(Mysqlitehelper.Table_grid, column_name, null, null, null, null, null, null);
if(cursor.moveToFirst())
do{
String path = new String();
path=cursor.getString(1);
pathlist.add(path);
}while(cursor.moveToNext());
cursor.close();
return pathlist;
}
}
please help me to find solution

Your adapter needs work. WIthin your getView() method you assume the arguments are a URI. IN fact, the arguments are:
public View getView(final int position, View convertView, final ViewGroup parent) {
...
}
The first argument, is the position of the item in the gridview you're about to render. The 2nd is the View - which may be recycled. And the 3rd is the parent of the view. You are trying to take the position, a simple integer, and use that as a URI
What you should be doing within your getView is pulling the image out of your database that corresponds to the "position"th item
See this link here for more information on developing loaders for your adapters

Related

SearchView in CustomAdapter

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

onItemClick in list doesnot open selected item in viewpager

onItemClick doesnot open selected item in viewpager
I have a list view which is populated using a sqlite db with a helperclass
when we click on a item in listview it should open the viewpager class and we can swipe through various details
the viewpager opens but always starts from the first list item
even though I have set the
Bundle b = getIntent().getExtras();
int index = b.getInt("position");
mViewPager.setCurrentItem(index);
I want to open the viewpager with the item that I have selected and not start from the first entry each time.
here is the listactivity
public class MyActivity extends Activity {
private CustomCursorAdapter customAdapter;
private PersonDatabaseHelper databaseHelper;
private static final int ENTER_DATA_REQUEST_CODE = 1;
private ListView listView;
private static final String TAG = MyActivity.class.getSimpleName();
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
databaseHelper = new PersonDatabaseHelper(this);
listView = (ListView) findViewById(R.id.list_data);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Log.d(TAG, "clicked on item: " + position);
Toast.makeText(getApplicationContext(), "aa" + position,
Toast.LENGTH_LONG).show();
//startActivity(new Intent(getApplicationContext(), viepagerActivity.class));
Intent i = new Intent(MyActivity.this, viepagerActivity.class);
i.putExtra("position", position);
MyActivity.this.startActivity(i);
}
});
new Handler().post(new Runnable() {
#Override
public void run() {
customAdapter = new CustomCursorAdapter(MyActivity.this,
databaseHelper.getAllData());
listView.setAdapter(customAdapter);
}
});
}
public void onClickEnterData(View btnAdd) {
startActivityForResult(new Intent(this, EnterDataActivity.class),
ENTER_DATA_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ENTER_DATA_REQUEST_CODE && resultCode == RESULT_OK) {
databaseHelper.insertData(
data.getExtras().getString("tag_person_name"), data
.getExtras().getString("tag_person_pin"));
customAdapter.changeCursor(databaseHelper.getAllData());
}
}
}
adapter
public class CustomCursorAdapter extends CursorAdapter {
public CustomCursorAdapter(Context context, Cursor c) {
super(context, c);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// when the view will be created for first time,
// we need to tell the adapters, how each item will look
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View retView = inflater
.inflate(R.layout.single_row_item, parent, false);
return retView;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
// here we are setting our data
// that means, take the data from the cursor and put it in views
TextView textViewPersonName = (TextView) view
.findViewById(R.id.tv_person_name);
textViewPersonName.setText(cursor.getString(cursor
.getColumnIndex(cursor.getColumnName(1))));
TextView textViewPersonPIN = (TextView) view
.findViewById(R.id.tv_person_pin);
textViewPersonPIN.setText(cursor.getString(cursor.getColumnIndex(cursor
.getColumnName(2))));
}
}
The viewpager
public class viepagerActivity extends Activity {
private List<String> testContactName = new ArrayList<String>();
private List<String> testContactNumber = new ArrayList<String>();
MyAdapter mAdapter;
private PersonDatabaseHelper databaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main1);
databaseHelper = new PersonDatabaseHelper(this);
ViewPager mViewPager = (ViewPager) findViewById(R.id.pager);
mAdapter = new MyAdapter();
mViewPager.setAdapter(mAdapter);
Bundle b = getIntent().getExtras();
int index = b.getInt("position");
mViewPager.setCurrentItem(index);
Toast.makeText(getApplicationContext(), "viepager" + index, Toast.LENGTH_LONG)
.show();
try {
getAllContacts();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void getAllContacts() {
SQLiteDatabase db = databaseHelper.database;
String[] columns = { PersonDatabaseHelper.PERSON_TABLE_COLUMN_ID,
PersonDatabaseHelper.PERSON_TABLE_COLUMN_NAME,
PersonDatabaseHelper.PERSON_TABLE_COLUMN_PIN, };
Cursor cursor = db.query(PersonDatabaseHelper.TABLE_NAME, columns,
null, null, null, null, null, null);
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndex(cursor
.getColumnName(1)));
String phoneNumber = cursor.getString(cursor.getColumnIndex(cursor
.getColumnName(2)));
testContactName.add(name);
mAdapter.notifyDataSetChanged();
testContactNumber.add(phoneNumber);
mAdapter.notifyDataSetChanged();
}
cursor.close();
}
private class MyAdapter extends PagerAdapter {
public MyAdapter() {
super();
}
#Override
public int getCount() {
return testContactName.size();
}
#Override
public boolean isViewFromObject(View collection, Object object) {
return collection == ((View) object);
}
#Override
public Object instantiateItem(View collection, int position) {
Bundle b = getIntent().getExtras();
LayoutInflater inflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.viewpager_items, null);
TextView contactName = (TextView) view.findViewById(R.id.labelText);
TextView contactNumber = (TextView) view
.findViewById(R.id.answerText);
try {
contactName.setText(testContactName.get(position));
contactNumber.setText(testContactNumber.get(position));
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
((ViewPager) collection).addView(view, 0);
return view;
}
#Override
public void destroyItem(View collection, int position, Object view) {
((ViewPager) collection).removeView((View) view);
mAdapter.notifyDataSetChanged();
}
}
}
the helper class
public class PersonDatabaseHelper {
public static final String TAG = PersonDatabaseHelper.class
.getSimpleName();
// database configuration
// if you want the onUpgrade to run then change the database_version
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "mydatabase.db";
// table configuration
public static final String TABLE_NAME = "person_table"; // Table name
public static final String PERSON_TABLE_COLUMN_ID = "_id"; // a column
// named "_id"
// is required
// for cursor
public static final String PERSON_TABLE_COLUMN_NAME = "person_name";
public static final String PERSON_TABLE_COLUMN_PIN = "person_pin";
public DatabaseOpenHelper openHelper;
public SQLiteDatabase database;
// this is a wrapper class. that means, from outside world, anyone will
// communicate with PersonDatabaseHelper,
// but under the hood actually DatabaseOpenHelper class will perform
// database CRUD operations
public PersonDatabaseHelper(Context aContext) {
openHelper = new DatabaseOpenHelper(aContext);
database = openHelper.getWritableDatabase();
}
public void insertData(String aPersonName, String aPersonPin) {
// we are using ContentValues to avoid sql format errors
ContentValues contentValues = new ContentValues();
contentValues.put(PERSON_TABLE_COLUMN_NAME, aPersonName);
contentValues.put(PERSON_TABLE_COLUMN_PIN, aPersonPin);
database.insert(TABLE_NAME, null, contentValues);
}
public Cursor getAllData() {
String buildSQL = "SELECT * FROM " + TABLE_NAME;
Log.d(TAG, "getAllData SQL: " + buildSQL);
return database.rawQuery(buildSQL, null);
}
// this DatabaseOpenHelper class will actually be used to perform database
// related operation
private class DatabaseOpenHelper extends SQLiteOpenHelper {
public DatabaseOpenHelper(Context aContext) {
super(aContext, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
// Create your tables here
String buildSQL = "CREATE TABLE " + TABLE_NAME + "( "
+ PERSON_TABLE_COLUMN_ID + " INTEGER PRIMARY KEY, "
+ PERSON_TABLE_COLUMN_NAME + " TEXT, "
+ PERSON_TABLE_COLUMN_PIN + " TEXT )";
Log.d(TAG, "onCreate SQL: " + buildSQL);
sqLiteDatabase.execSQL(buildSQL);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion,
int newVersion) {
// Database schema upgrade code goes here
String buildSQL = "DROP TABLE IF EXISTS " + TABLE_NAME;
Log.d(TAG, "onUpgrade SQL: " + buildSQL);
sqLiteDatabase.execSQL(buildSQL); // drop previous table
onCreate(sqLiteDatabase); // create the table from the beginning
}
}
}

how to display data from sqlite in custom listfragment

I want to display data from sqlite database and I will show to listfragment, but until now have not been able to be displayed
Class Barang.java
public class Barang {
private long id;
private String nama_barang;
private String merk_barang;
private String harga_barang;
public Barang()
{
}
/**
* #return the id
*/
public long getId() {
return id;
}
/**
* #param id the id to set
*/
public void setId(long id) {
this.id = id;
}
/**
* #return the nama_barang
*/
public String getNama_barang() {
return nama_barang;
}
/**
* #param nama_barang the nama_barang to set
*/
public void setNama_barang(String nama_barang) {
this.nama_barang = nama_barang;
}
/**
* #return the merk_barang
*/
public String getMerk_barang() {
return merk_barang;
}
/**
* #param merk_barang the merk_barang to set
*/
public void setMerk_barang(String merk_barang) {
this.merk_barang = merk_barang;
}
/**
* #return the harga_barang
*/
public String getHarga_barang() {
return harga_barang;
}
/**
* #param harga_barang the harga_barang to set
*/
public void setHarga_barang(String harga_barang) {
this.harga_barang = harga_barang;
}
#Override
public String toString()
{
return id +" "+ nama_barang +" "+ merk_barang + " "+ harga_barang;
}
}
DBHelper.java
public class DBHelper extends SQLiteOpenHelper{
public static final String TABLE_NAME = "data_inventori";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_NAME = "nama_barang";
public static final String COLUMN_MERK = "merk_barang";
public static final String COLUMN_HARGA = "harga_barang";
private static final String db_name ="inventori.db";
private static final int db_version=1;
private static final String db_create = "create table "
+ TABLE_NAME + "("
+ COLUMN_ID +" integer primary key autoincrement, "
+ COLUMN_NAME+ " varchar(50) not null, "
+ COLUMN_MERK+ " varchar(50) not null, "
+ COLUMN_HARGA+ " varchar(50) not null);";
public DBHelper(Context context) {
super(context, db_name, null, db_version);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(db_create);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
Log.w(DBHelper.class.getName(),"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
DBDataSource.java
public class DBDataSource {
private SQLiteDatabase database;
private DBHelper dbHelper;
private String[] allColumns = { DBHelper.COLUMN_ID,
DBHelper.COLUMN_NAME, DBHelper.COLUMN_MERK,DBHelper.COLUMN_HARGA};
public DBDataSource(Context context)
{
dbHelper = new DBHelper(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public Barang createBarang(String nama, String merk, String harga) {
ContentValues values = new ContentValues();
values.put(DBHelper.COLUMN_NAME, nama);
values.put(DBHelper.COLUMN_MERK, merk);
values.put(DBHelper.COLUMN_HARGA, harga);
long insertId = database.insert(DBHelper.TABLE_NAME, null,
values);
Cursor cursor = database.query(DBHelper.TABLE_NAME,
allColumns, DBHelper.COLUMN_ID + " = " + insertId, null,
null, null, null);
cursor.moveToFirst();
Barang newBarang = cursorToBarang(cursor);
cursor.close();
return newBarang;
}
private Barang cursorToBarang(Cursor cursor)
{
Barang barang = new Barang();
barang.setId(cursor.getLong(0));
barang.setNama_barang(cursor.getString(1));
barang.setMerk_barang(cursor.getString(2));
barang.setHarga_barang(cursor.getString(3));
return barang;
}
public ArrayList<Barang> getAllBarang() {
ArrayList<Barang> daftarBarang = new ArrayList<Barang>();
Cursor cursor = database.query(DBHelper.TABLE_NAME,
allColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Barang barang = cursorToBarang(cursor);
daftarBarang.add(barang);
cursor.moveToNext();
}
cursor.close();
return daftarBarang;
}
public Barang getBarang(long id)
{
Barang barang = new Barang();
Cursor cursor = database.query(DBHelper.TABLE_NAME, allColumns, "_id ="+id, null, null, null, null);
cursor.moveToFirst();
barang = cursorToBarang(cursor);
cursor.close();
return barang;
}
public void updateBarang(Barang b)
{
String strFilter = "_id=" + b.getId();
ContentValues args = new ContentValues();
args.put(DBHelper.COLUMN_NAME, b.getNama_barang());
args.put(DBHelper.COLUMN_MERK, b.getMerk_barang());
args.put(DBHelper.COLUMN_HARGA, b.getHarga_barang() );
database.update(DBHelper.TABLE_NAME, args, strFilter, null);
}
public void deleteBarang(long id)
{
String strFilter = "_id=" + id;
database.delete(DBHelper.TABLE_NAME, strFilter, null);
}
}
MasterBarang.java
public class MasterBarang extends ListFragment implements OnItemLongClickListener {
private DBDataSource dataSource;
private ImageButton bTambah;
private ArrayList<Barang> values;
private Button editButton;
private Button delButton;
private AlertDialog.Builder alertDialogBuilder;
public MasterBarang(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_masterbarang, container, false);
bTambah = (ImageButton) rootView.findViewById(R.id.button_tambah);
bTambah.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), CreateData.class);
startActivity(intent);
getActivity().finish();
}
});
ListView lv = (ListView) rootView.findViewById(android.R.id.list);
lv.setOnItemLongClickListener(this);
return rootView;
}
public void OnCreate(Bundle savedInstanceStat){
dataSource = new DBDataSource(getActivity());
dataSource.open();
values = dataSource.getAllBarang();
ArrayAdapter<Barang> adapter = new ArrayAdapter<Barang>(getActivity(),
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
}
#Override
public boolean onItemLongClick(final AdapterView<?> adapter, View v, int pos,
final long id) {
final Barang b = (Barang) getListAdapter().getItem(pos);
alertDialogBuilder.setTitle("Peringatan");
alertDialogBuilder
.setMessage("Pilih Aksi")
.setCancelable(false)
.setPositiveButton("Ubah",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
switchToEdit(b.getId());
dialog.dismiss();
}
})
.setNegativeButton("Hapus",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dataSource.deleteBarang(b.getId());
dialog.dismiss();
getActivity().finish();
startActivity(getActivity().getIntent());
}
}).create().show();
return false;
}
public void switchToEdit(long id)
{
Barang b = dataSource.getBarang(id);
Intent i = new Intent(getActivity(), EditData.class);
Bundle bun = new Bundle();
bun.putLong("id", b.getId());
bun.putString("nama", b.getNama_barang());
bun.putString("merk", b.getMerk_barang());
bun.putString("harga", b.getHarga_barang());
i.putExtras(bun);
finale();
startActivity(i);
}
public void finale()
{
MasterBarang.this.getActivity().finish();
dataSource.close();
}
#Override
public void onResume() {
dataSource.open();
super.onResume();
}
#Override
public void onPause() {
dataSource.close();
super.onPause();
}
}
in simple not displayed
Here is the example code.
First create a layout for one list row.
example : list_row.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="8dp"
>
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textStyle="bold" />
<TextView
android:id="#+id/merk"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/name"
android:layout_marginTop="5dp" />
<TextView
android:id="#+id/harga"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/merk"
android:layout_marginTop="5dp"/>
</RelativeLayout>
After creating this list_row.xml layout, create a adapter class.
create CustomListAdapter.java
public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private ArrayList<Barang> barangList;
public CustomListAdapter(Activity activity, ArrayList<Barang> barangList) {
this.activity = activity;
this.barangList = barangList;
}
/*
get count of the barangList
*/
#Override
public int getCount() {
return barangList.size();
}
#Override
public Object getItem(int location) {
return barangList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
/*
inflate the items in the list view
*/
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null) {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_row, null);
}
/*
creating objects to access the views
*/
TextView name = (TextView) convertView.findViewById(R.id.name);
TextView merk = (TextView) convertView.findViewById(R.id.merk);
TextView harga = (TextView) convertView.findViewById(R.id.harga);
// getting barang data for the row
Barang barang = barangList.get(position);
name.setText(barang.getNama_barang());
merk.setText(barang.getMerk_barang());
harga.setText(barang.getHarga_barang());
return convertView;
}}
Now in your MasterBarang.java, put the following code in your onCreate method.
values = dataSource.getAllBarang();
CustomListAdapter adapter;
adapter = new CustomListAdapter(getActivity(), values);
setListAdapter(adapter);
Now run the application.. Cheers !
You are using simple list templete as a list view. But in case of custom list view, you should create your custom list model and "BaseAdapter" for the custom list model.
Below links will help you to make custom list view in easier way.
https://www.caveofprogramming.com/guest-posts/custom-listview-with-imageview-and-textview-in-android.html
http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/
The problem is you are closing your database in onPause() method, so the reference of the database will get destroyed. Then, you again trying to open the database in onResume() method. So here the null pointer exception occurs.
Solution:
change your onResume() method like this.
#Override
public void onResume() {
dataSource = new DBDataSource(getActivity());
dataSource.open();
super.onResume();
}
Now check it and if you got any error please post it here,.

How do I get the SQLite Database row_ID from the Gridview with onClicklistener?

First of all, I am able to load the image paths that are stored in SQLite Database into the Gridview, but I can't seem to find a way to get the position of the image path based on the SQLite Database row_ID from the Gridview with onClicklistener for deleting purposes.
I've tried this:
//CHECKBOXES ONCLICKLISTENER
AdapterView.OnItemClickListener Checkbox_MulClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
adapter.changeSelection(v, position);
System.out.println("position : " + position);
return;
}
};
But it always gives me the position started from 0 regardless of the SQLite Database row_ID.
My goal is to get the position of the image path from the Gridview with onClicklistener based on the row_ID's in the SQLite Database.
For example,
SQLite Database:
row_id:
3
4
5
when I click on the image from the Gridview,
it would give me the row_id started from 3 instead of 0.
SQLite_Database.java:
public class SQLite_Database extends SQLiteOpenHelper {
private static final String KEY_ID = "ROW_ID";
private static final String KEY_IMAGE = "image_file";
private static final String DATABASE_NAME = "imagesdb";
private static final int DATABASE_VERSION = 1;
private static final String IMAGES_TABLE_NAME = "images";
private static final String IMAGES_TABLE_CREATE =
"CREATE TABLE " + IMAGES_TABLE_NAME + "("+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_IMAGE + " TEXT);";
ViewSwitcher viewSwitcher;
Gallery_Adapter_Activity adapter;
public SQLite_Database(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(IMAGES_TABLE_CREATE);
db.execSQL(COUNT_TABLE_CREATE);
}
public void addImageFile(String file) {
ContentValues values = new ContentValues();
values.put(KEY_IMAGE, file);
getWritableDatabase().insert(IMAGES_TABLE_NAME, null, values);
}
public ArrayList<SDcardPath_Activity> readImageFiles() { //(0) //(1)
Cursor cursor = getReadableDatabase().query(IMAGES_TABLE_NAME, new String[] { KEY_ID, KEY_IMAGE }, null,
null, null, null, null);
try {
if (!cursor.moveToFirst()) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(IMAGES_TABLE_NAME, null, null);
db.close();
}
ArrayList<SDcardPath_Activity> sdcardPath_SQLite_Path = new ArrayList<SDcardPath_Activity>();
do {
String SQ_single_key_id = cursor.getString(0);
String SQ_single_path = cursor.getString(1);
Shared_Data_Class shared_data_class = new Shared_Data_Class(); SDcardPath_Activity SQ_SDcardPath_Class = new SDcardPath_Activity();
shared_data_class.putID(Integer.parseInt(SQ_single_key_id));
SQ_SDcardPath_Class.sdcardPath = SQ_single_path;
sdcardPath_SQLite_Path.add(SQ_SDcardPath_Class);
} while (cursor.moveToNext());
return sdcardPath_SQLite_Path;
}
finally {
cursor.close();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
// on upgrade drop older tables
db.execSQL("DROP TABLE IF EXISTS " + IMAGES_TABLE_CREATE);
// create new tables
onCreate(db);
}
// Deleting single SQLite_data
public void delete_SQLite_data(Shared_Data_Class shared_data_class) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(IMAGES_TABLE_NAME, KEY_ID + " = ?", new String[] {
String.valueOf(shared_data_class.read_String_method()) });
db.close();
}
}
Image_MainActivity.java:
public class Image_MainActivity extends Activity {
ArrayList<Shared_Data_Class> Shared_Data_Class_DATA = new ArrayList<Shared_Data_Class>();
GridView gridGallery;
Handler handler;
Gallery_Adapter_Activity adapter;
Button add_images_btn;
ViewSwitcher viewSwitcher;
ImageLoader imageLoader;
SQLite_Database SQ_LITE_DATABASE;
int add_image_count;
int result_requestcode = 542182;
public boolean isSeleted;
public String sdcardPath;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
initImageLoader();
init();
//Initialize other classes (or else error will occur)
SQ_LITE_DATABASE = new SQLite_Database(Image_MainActivity.this);
//LOAD IMAGE PATHS FROM SQLITE_DATABASE TO THE GRIDVIEW
try {
ArrayList<SDcardPath_Activity> SQLite_Databse_Data = SQ_LITE_DATABASE.readImageFiles();
viewSwitcher.setDisplayedChild(0);
adapter.addAll(SQLite_Databse_Data);
} catch (Exception e)
{
e.printStackTrace();
return;
}
Button delete = (Button) findViewById(R.id.delete);
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
private void initImageLoader() {
#SuppressWarnings("deprecation")
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder().cacheOnDisc().imageScaleType
(ImageScaleType.EXACTLY_STRETCHED).bitmapConfig(Bitmap.Config.RGB_565).build();
ImageLoaderConfiguration.Builder builder = new ImageLoaderConfiguration.Builder(
this).defaultDisplayImageOptions(defaultOptions).memoryCache(new WeakMemoryCache());
ImageLoaderConfiguration config = builder.build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
}
//CHECKBOXES ONCLICKLISTENER
AdapterView.OnItemClickListener Checkbox_MulClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
adapter.changeSelection(v, position);
System.out.println("position : " + position);
return;
}
};
private void init() {
handler = new Handler();
gridGallery = (GridView) findViewById(R.id.main_gridGallery);
gridGallery.setFastScrollEnabled(true); //To have fast scroll bar on the screen
adapter = new Gallery_Adapter_Activity(getApplicationContext(), imageLoader);
gridGallery.setOnItemClickListener(Checkbox_MulClickListener); //for checkboxes OnItemClickListener
adapter.setMultiplePick(true); //Turn on checkboxes in Image_MainActivity Class
gridGallery.setAdapter(adapter);
viewSwitcher = (ViewSwitcher) findViewById(R.id.viewSwitcher);
viewSwitcher.setDisplayedChild(1);
Button done_button = (Button) findViewById(R.id.done);
done_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { //Done Button OnClickListener
finish();
}
});
add_images_btn = (Button) findViewById(R.id.add_images_button);
add_images_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { //Add Images Button OnClickListener
Intent i = new Intent(Multiple_Pick_Activity.ACTION_MULTIPLE_PICK);
startActivityForResult(i, result_requestcode);
//result_requestcode is the sent code. The request code must match
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//result_requestcode is the sent code. The request code must match
if (requestCode == result_requestcode && resultCode == Activity.RESULT_OK)
//RESULT_OK is from Gallery_View_Activity
{
SDcardPath_Activity SDcardPath_Class = new SDcardPath_Activity();
String[] ALL_Paths = data.getStringArrayExtra("all_path");
for (String single_path : ALL_Paths)
{
SQ_LITE_DATABASE.addImageFile(single_path); // Add single_path to method addImageFile() {
// in SQLite_Database class
}
try {
ArrayList<SDcardPath_Activity> SQLite_Databse_Data = SQ_LITE_DATABASE.readImageFiles();
SQLite_Databse_Data.add(SDcardPath_Class);
viewSwitcher.setDisplayedChild(0);
adapter.addAll(SQLite_Databse_Data);
Intent intent = new Intent (Image_MainActivity.this, Image_MainActivity.class);
startActivity(intent);
finish();
} catch (Exception e)
{
e.printStackTrace();
return;
}
}
}
If someone can help me, it would be greatly appreciated.
Thank you very much.
edit: added
Gallery_Adapter_Activity.java
#Override
public int getCount() {
return data.size();
}
#Override
public SDcardPath_Activity getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public void setMultiplePick(boolean isMultiplePick) {
this.isActionMultiplePick = isMultiplePick;
}
public void selectAll(boolean selection) {
for (int i = 0; i < data.size(); i++) {
data.get(i).isSeleted = selection;
}
notifyDataSetChanged();
}
You should pass into your adapter an arraylist of model objects; call it myArray. Populate the array with model objects that have a reference to the path you want. Then you can call myArray.get(position), that will give you a model object; call it myObject. Then call myObject.getPath().
Model Object: a class you create that has closely related data you want to retrieve (see http://www.javapractices.com/topic/TopicAction.do?Id=187), in this case it will have a reference to a picture location. You should put in your model class setters and getters for each field. Your class will have a field that holds a reference to the path to your image.
Something like:
class MyPic {
private String path;
public MyPic(String path){
this.path = path;
}
public getPath(){
return path;
}
etc . . .
}

Delete view from ListView

i would like to know the best possible way do delete a TextView from ListView,
But i want to do it from Options Menu.
so i click "Delete Country" - it will wait untill i will tap a country than delete the tapped country.
i am new to programming. thanks in advance
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.omAddCountry:
Intent addCountryIntent = new Intent(MainActivity.this, AddCountryActivity.class);
startActivityForResult(addCountryIntent, 11);
break;
case R.id.omDeleteCountry:
break;
the ListView is using SQLite and it gets the first view from DB and the TextViews is added by an Vector from an adapter.
public class CountryAdapter extends BaseAdapter {
private Context mContext;
protected Vector<Country> mVector;
protected SQLiteDatabase mDb;
public void setmContext(Context mContext){
this.mContext = mContext;
}
public CountryAdapter(Context mContext){
this.mContext = mContext;
mVector = new Vector<Country>();
CountryOpenHelper helper = new CountryOpenHelper(mContext);
mDb = helper.getWritableDatabase();
Cursor cursor = mDb.rawQuery("SELECT * FROM COUNTRIES", null);
if(cursor.getCount() > 0){
cursor.moveToFirst();
}
do {
Country country = new Country();
country.setmCountryIndex(cursor.getInt(0));
country.setmCountryName(cursor.getString(2));
country.setmCountryTextSize(cursor.getInt(1));
country.setmCountryColor(cursor.getInt(3));
mVector.add(country);
} while (cursor.moveToNext());
}
public Vector<Country> getmVector() {
return mVector;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mVector.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView tv;
if(convertView == null){
tv = new TextView(mContext);
}else{
tv = (TextView) convertView;
}
tv.setText(mVector.get(position).getmCountryName());
tv.setTextColor(mVector.get(position).getmCountryColor());
tv.setTextSize(mVector.get(position).getmCountryTextSize());
return tv;
}
public void ChangeColor(int newcolor, String name) {
mDb.execSQL("update COUNTRIES set color = " + newcolor + " where name = '" + name + "' " );
}
public void addCountry(int mId, String myCountry, int myColorNum){
mDb.execSQL("insert into countries values(" + mId + " , ' " + myCountry+"' , "+ myColorNum + ")");
}
}
Make a global boolean:
boolean isDeleting = false;
then in onOptionsItemSelected(), do:
case R.id.omDeleteCountry:
isDeleting = true;
break;
And whereever you implement onListItemClick():
#Override
public void onListItemClick (ListView listView,View view, int pos, long id)
{
if (isDeleting){
yourCustomAdapter.delete(pos)
yourCustomAdapter.notifyDataSetChanged();
isDeleting = false;
}
else {
//do other stuff
}
}
You will have to make a delete() method in your adapter.

Categories

Resources