SearchView in CustomAdapter - android

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

Related

By long clicking on listview delete its contents from SQLite and listview that is clicked

Can anyone show me how to delete contents from an SQLite database and listview by long clicking on it? Also, do I have to delete only contents from SQLite database or from both SQLite database and listview?
Here are my project classes:
Database Helper
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 3;
private static final String DATABASE_NAME = "products.db";
private static final String TABLE_NAME = "products";
private static final String COLUMN_ID = "_id";
private static final String MARKET = "market";
private static final String PRODUCT = "product";
private SQLiteDatabase db;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ MARKET + " TEXT, "
+ PRODUCT + " TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME + "");
onCreate(db);
}
public Cursor getRecords() {
db = getReadableDatabase();
return db.rawQuery(
"SELECT * FROM " + TABLE_NAME,
null);
}
public void addRecords(String market, String product) {
db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(MARKET, market);
contentValues.put(PRODUCT, product);
db.insert(TABLE_NAME, null, contentValues);
db.close();
}
public void deleteRecords(int id){
}}
MainActivity
public class MainActivity extends AppCompatActivity {
ListView lv;
DatabaseHelper databaseHelper;
ShoppingCartAdapter shoppingCartAdapter;
private static final int TIME_ENTRY_REQUEST_CODE = 1;
Cursor cursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.list_view_main);
databaseHelper = new DatabaseHelper(this);
ListView listView = (ListView) findViewById(R.id.list_view_main);
shoppingCartAdapter = new ShoppingCartAdapter(this, databaseHelper.getRecords(), CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
listView.setAdapter(shoppingCartAdapter);
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(final AdapterView<?> parent, View view, int position, long id) {
final int pos = position;
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Are you sure you want to delete?");
builder.setPositiveButton("DELETE", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder.setNegativeButton("CANCEL", null);
builder.show();
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu_template, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.menu_add_id) {
Intent intent = new Intent(this, AddContentActivity.class);
startActivityForResult(intent, TIME_ENTRY_REQUEST_CODE);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == TIME_ENTRY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
String market = data.getStringExtra("market");
String product = data.getStringExtra("product");
databaseHelper.addRecords(market, product);
shoppingCartAdapter.changeCursor(databaseHelper.getRecords());
}
}
}
}
AddContentActivity
public class AddContentActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addcontent);
}
public void onAddButton(View view){
Intent intent = getIntent();
EditText marketet = (EditText) findViewById(R.id.marketet_id);
EditText productet = (EditText) findViewById(R.id.productet_id);
intent.putExtra("market", marketet.getText().toString());
intent.putExtra("product", productet.getText().toString());
this.setResult(RESULT_OK, intent);
finish();
}
}
ShoppingCartAdapter
public class ShoppingCartAdapter extends CursorAdapter{
public ShoppingCartAdapter(Context context, Cursor cursor, int flags){
super(context, cursor, flags);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView marketTv = (TextView) view.findViewById(R.id.markettv_id);
TextView productTv = (TextView) view.findViewById(R.id.producttv_id);
marketTv.setText(cursor.getString(1));
productTv.setText(cursor.getString(2));
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.list_view_template, parent, false);
return view;
}
}
After couple of days I found solution on my question.If there is better way of doing delete, please post answer.
I added following lines of code:
Main Activity
Cursor cursor = (Cursor) parent.getItemAtPosition(pos);
final int item_id = cursor.getInt(cursor.getColumnIndex("_id"));
databaseHelper.deleteRecords(item_id );
cursor.requery();
DatabaseHelper
public void deleteRecords(int id){
db.delete(TABLE_NAME, COLUMN_ID + "=" + id, null);
}
EDIT:
replaced cursor.requery(); with
shoppingCartAdapter.changeCursor(databaseHelper.getRecords());
because using requery(); is deprecated but both lines of code work.

How to read,add Database into ArrayList?

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

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

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

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

Categories

Resources