i am having a list view. like this. I want to make the second item in the list view to be burled or color changed when loading the activity.
here is my code
Activity on create method
list_all_visits(schedule_id);
List Adapter
private void list_all_visits(int schedule_id){
mvisitsDAO =new VisitsDAO(getApplicationContext());
ListVisits = mvisitsDAO.getAllvisitsforSchedule(schedule_id);
ArrayAdapter<Visits> adapter = new ArrayAdapter<Visits>(this, R.layout.schedule_layout_list, R.id.tv_text1, ListVisits);
setListAdapter(adapter);
}
visitsDAO
package lk.agent.certislanka.certisagenttracking.data;
/**
* Created by administrator on 7/7/15.
*/
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import lk.agent.certislanka.certisagenttracking.model.Visits;
/**
* Created by administrator on 7/6/15.
*/
public class VisitsDAO {
public static final String TAG = "visitsDAO";
// Database fields
private SQLiteDatabase mDatabase;
private DBHelper mDbHelper;
private Context mContext;
private String[] mAllColumns = {
DBHelper.COLUMN_VISITS_ID,
DBHelper.COLUMN_VISITS_SCHEDULE_ID,
DBHelper.COLUMN_VISITS_NAME,
DBHelper.COLUMN_VISITS_TIME,
DBHelper.COLUMN_VISITS_PLACE,
DBHelper.COLUMN_VISITS_ADDRESS,
DBHelper.COLUMN_VISITS_TEL,
DBHelper.COLUMN_VISITS_LOCATION_LAT,
DBHelper.COLUMN_VISITS_LOCATION_LNG,
DBHelper.COLUMN_VISITS_STATUS };
public VisitsDAO(Context context) {
this.mContext = context;
mDbHelper = new DBHelper(context);
// open the database
try {
open();
} catch (SQLException e) {
Log.e(TAG, "SQLException on openning database " + e.getMessage());
e.printStackTrace();
}
}
public void open() throws SQLException {
mDatabase = mDbHelper.getWritableDatabase();
}
public void close() {
mDbHelper.close();
}
public Visits createvisits(int vid, int v_sid, String vname, String vtime, String vplace, String address, String telephone, String vlat, String vlong, int vstatus) {
ContentValues values = new ContentValues();
values.put(DBHelper.COLUMN_VISITS_ID, vid);
values.put(DBHelper.COLUMN_VISITS_SCHEDULE_ID, v_sid);
values.put(DBHelper.COLUMN_VISITS_NAME, vname);
values.put(DBHelper.COLUMN_VISITS_TIME, vtime);
values.put(DBHelper.COLUMN_VISITS_PLACE, vplace);
values.put(DBHelper.COLUMN_VISITS_ADDRESS, address);
values.put(DBHelper.COLUMN_VISITS_TEL, telephone);
values.put(DBHelper.COLUMN_VISITS_LOCATION_LAT, vlat);
values.put(DBHelper.COLUMN_VISITS_LOCATION_LNG, vlong);
values.put(DBHelper.COLUMN_VISITS_STATUS, vstatus);
long insertId = mDatabase
.insert(DBHelper.TABLE_VISITS, null, values);
Cursor cursor = mDatabase.query(DBHelper.TABLE_VISITS, mAllColumns,
DBHelper.COLUMN_VISITS_ID + " = " + insertId, null, null,
null, null);
Visits newvisits = null;
if (cursor != null&& cursor.moveToFirst()) {
cursor.moveToFirst();
newvisits = cursorTovisits(cursor);
}
cursor.close();
return newvisits;
}
public List<Visits> getAllvisits() {
List<Visits> listVisits = new ArrayList<Visits>();
Cursor cursor = mDatabase.query(DBHelper.TABLE_VISITS, mAllColumns,
null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Visits visits = cursorTovisits(cursor);
listVisits.add(visits);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
}
return listVisits;
}
public List<Visits> getAllvisitsforSchedule(int id) {
List<Visits> listVisits = new ArrayList<Visits>();
Cursor cursor = mDatabase.query(DBHelper.TABLE_VISITS, mAllColumns,
DBHelper.COLUMN_VISITS_SCHEDULE_ID + " = ?",
new String[]{String.valueOf(id)}, null, null, "visit_time ASC");
if (cursor != null) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Visits visits = cursorTovisits(cursor);
listVisits.add(visits);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
}
return listVisits;
}
public Visits getvisitById(int id) {
Cursor cursor = mDatabase.query(DBHelper.TABLE_VISITS, mAllColumns,
DBHelper.COLUMN_VISITS_ID + " = ?",
new String[]{String.valueOf(id)}, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
Visits visits = cursorTovisits(cursor);
return visits;
}
protected Visits cursorTovisits(Cursor cursor) {
Visits schedule = new Visits();
schedule.setvId(cursor.getInt(0));
schedule.setVschID(cursor.getInt(1));
schedule.setVname(cursor.getString(2));
schedule.setVtime(cursor.getString(3));
schedule.setVplace(cursor.getString(4));
schedule.setVaddress(cursor.getString(5));
schedule.setvtelephone(cursor.getString(6));
schedule.setVlat(cursor.getString(7));
schedule.setVlong(cursor.getString(8));
schedule.setVstatus(cursor.getInt(9));
return schedule;
}
public void deleteVisits(Visits visits) {
int id = visits.getvId();
mDatabase.delete(DBHelper.TABLE_VISITS, DBHelper.COLUMN_VISITS_ID + " = " + id, null);
}
public void deleteAllVisits() {
SQLiteDatabase db = mDbHelper.getWritableDatabase();
db.delete(DBHelper.TABLE_VISITS, null, null);
}
}
You just have to set whatever properties you want for textview, imageview, layout etc. in getView() methos of your list adapter.
For example refer the below code,
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView ;
if( convertView == null ) {
imageView = new ImageView(context);
imageView.setLayoutParams(
new ListView.LayoutParams( 80,80 )
);
}
else {
imageView = (ImageView) convertView;
}
imageView.setImageResource( imageIds[position] );
imageView.setEnabled(false);
return imageView;
}
Where I have written imageView.setEnabled(false), you can give whatever properties to your views ( like layout.setBackground(Color.RED); )
Related
Im trying to find all mp3 files but a have no idea and I found this code, the only problem is the getActivity() wasn't declared, I don't how know to fix, please help me. If has the better way of to do this, I accept sugestion.
here is my class:
public class SongsManager {
private ArrayList<Song> songsList;
public void getMp3Songs() {
Uri allSongsUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
Cursor cursor = getActivity().getContentResolver().query(allSongsUri, null, null, null, selection);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
Song song = new Song(cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media._ID)),
cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME)),
cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST)),
cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA)));
songsList.add(song);
// album_name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
// int album_id = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
// int artist_id = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST_ID));
} while (cursor.moveToNext());
}
cursor.close();
}
}
}
Set parameter for Method (getMp3Songs) as Context:
public class SongsManager {
private ArrayList<Song> songsList;
public void getMp3Songs(Context ctx) {
Uri allSongsUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
Cursor cursor = ctx.getContentResolver().query(allSongsUri, null, null, null, selection);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
Song song = new Song(cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media._ID)),
cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME)),
cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST)),
cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA)));
songsList.add(song);
// album_name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
// int album_id = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
// int artist_id = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST_ID));
} while (cursor.moveToNext());
}
cursor.close();
}
}
}
create Constructor and put there Context. And then call context instead of getActivity();
public class SongsManager {
private Context context;
public SongsManager(Context context){
this.context = context;
}
}
I have a list of invitees. I am using a recyclerview and custom adapter. In this I am getting the photo from contacts by a contactId fetched with contact number.
Now I as set the imageUri to the image view. Only one image is shown to all the rows for which the imageUri is not null. And the position changes as I scroll up and down. Sometimes it shows the image and sometimes it dose not.
I want set the uri as per the position of invitee. How to do this?
Adapter :
public class InviteeAdapter extends RecyclerView.Adapter<InviteeAdapter.MyViewHolder>{
private List<Invitee> inviteeList;
int status;
Context context;
Cursor mCursor;
private ArrayList<Uri> imageArray;
public String contactId;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView name;
public com.github.siyamed.shapeimageview.CircularImageView profileImage;
String mobileNo;
public MyViewHolder(View view) {
super(view);
name = (TextView) view.findViewById(R.id.scheduleName);
profileImage = (com.github.siyamed.shapeimageview.CircularImageView) view.findViewById(R.id.eventsIcon);
imageArray = new ArrayList<>();
}
public String fetchContactIdFromPhoneNumber(String phoneNumber) {
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(phoneNumber));
Cursor cursor = context.getContentResolver().query(uri,
new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.PhoneLookup._ID},
null, null, null);
String contactId = "";
if (cursor.moveToFirst()) {
do {
contactId = cursor.getString(cursor
.getColumnIndex(ContactsContract.PhoneLookup._ID));
} while (cursor.moveToNext());
}
return contactId;
}
}
public InviteeAdapter(List<Invitee> inviteeList,Context context) {
this.inviteeList = inviteeList;
this.context = context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.invitee_card, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Uri imageUri;
Invitee invitee = new Invitee();
invitee = inviteeList.get(position);
holder.name.setText(invitee.getFName()+" "+ invitee.getLName());
contactId = holder.fetchContactIdFromPhoneNumber(invitee.getMobile());
ArrayList<String> contactArray = new ArrayList<>();
imageUri = getPhotoUri();
imageArray.add(getPhotoUri());
contactArray.add(contactId);
for(Uri id : imageArray)
{
// imageUri = getPhotoUri();
if(imageUri!= null) {
holder.profileImage.setImageURI(id);
}
else {
holder.profileImage.setBackgroundResource(R.drawable.ic_person_black_48dp);
}
}
/* status = invitee.;
if(status == 0)
{
holder.name.setTextColor(context.getResources().getColor(R.color.colorAccent));
}
else {
holder.name.setTextColor(context.getResources().getColor(R.color.grey));
}*/
}
public Uri getPhotoUri() {
try {
Cursor cur = context.getContentResolver().query(
ContactsContract.Data.CONTENT_URI,
null,
ContactsContract.Data.CONTACT_ID + "=" + contactId + " AND "
+ ContactsContract.Data.MIMETYPE + "='"
+ ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE + "'", null,
null);
if (cur != null) {
if (!cur.moveToFirst()) {
return null; // no photo
}
} else {
return null; // error in cursor process
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
Uri person = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long
.parseLong(contactId));
return Uri.withAppendedPath(person, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
}
#Override
public int getItemCount() {
return inviteeList.size();
}
}
Can someone help please. Thank you..
Check this link it will help:
https://www.simplifiedcoding.net/android-custom-listview-with-images-using-recyclerview-and-volley/
I want to obtain a genre list using a recycler view and display them in a view pager ass grids. I have done this to retrieve albums but am confused about how to get genre from a track.
My album retrieval code:-
AlbumRetriever
public class AlbumLoader {
public static Album getAlbum(Cursor cursor) {
Album album = new Album();
if (cursor != null) {
if (cursor.moveToFirst())
album = new Album(cursor.getLong(0), cursor.getString(1), cursor.getString(2), cursor.getLong(3), cursor.getInt(4), cursor.getInt(5));
}
if (cursor != null)
cursor.close();
return album;
}
public static List<Album> getAlbumsForCursor(Cursor cursor) {
ArrayList arrayList = new ArrayList();
if ((cursor != null) && (cursor.moveToFirst()))
do {
arrayList.add(new Album(cursor.getLong(0),
cursor.getString(1),
cursor.getString(2),
cursor.getLong(3),
cursor.getInt(4),
cursor.getInt(5)));
}
while (cursor.moveToNext());
if (cursor != null)
cursor.close();
return arrayList;
}
public static List<Album> getAllAlbums(Context context) {
return getAlbumsForCursor(makeAlbumCursor(context, null, null));
}
public static Album getAlbum(Context context, long id) {
return getAlbum(makeAlbumCursor(context, "_id=?", new String[]{String.valueOf(id)}));
}
public static List<Album> getAlbums(Context context, String paramString) {
return getAlbumsForCursor(makeAlbumCursor(context,
"album LIKE ?",
new String[]{"%" + paramString + "%"}));
}
public static Cursor makeAlbumCursor(Context context, String selection, String[] paramArrayOfString) {
final String albumSortOrder = musixone.com.musixplayer.Utils
.PreferencesUtility.getInstance(context).getAlbumSortOrder();
Cursor cursor = context.getContentResolver().query(
MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
new String[]{"_id", "album", "artist", "artist_id", "numsongs", "minyear"},
selection, paramArrayOfString, albumSortOrder);
return cursor;
}
}
I have made an album class object too. How to go about retrieving the genres?
I am working with sqllite. I have successfully create a database and I can input some values in my database. I can also show all values in listview and also i can remove item by listview's onitemclicklistener.i have one problem. when i delete item listview not updated,but this item is deleted in database.how i can solve this problem ?
DatabaseHandler .java code
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "lvstone_2";
private static final String TABLE_CONTACTS = "CardTable1";
private static final String KEY_ID = "id";
private static final String KEY_Tittle = "name";
private static final String KEY_Description = "description";
private static final String KEY_Price = "price";
private static final String KEY_Counter = "counter";
private static final String KEY_Image = "image";
private final ArrayList<Contact> contact_list = new ArrayList<Contact>();
public static SQLiteDatabase db;
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_Tittle + " TEXT,"
+ KEY_Description + " TEXT,"
+ KEY_Price + " TEXT,"
+ KEY_Counter + " TEXT,"
+ KEY_Image + " TEXT"
+ ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
// Adding new contact
public void Add_Contact(Contact contact) {
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
if (!somethingExists(contact.getTitle())) {
values.put(KEY_Tittle, contact.getTitle()); // Contact title
values.put(KEY_Description, contact.getDescription()); // Contact//
// description
values.put(KEY_Price, contact.getPrice()); // Contact price
values.put(KEY_Counter, contact.getCounter()); // Contact image
values.put(KEY_Image, contact.getImage()); // Contact image
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
Log.e("Table Result isss", String.valueOf(values));
db.close(); // Closing database connection
}
}
public void deleteUser(String userName)
{
db = this.getWritableDatabase();
try
{
db.delete(TABLE_CONTACTS, "name = ?", new String[] { userName });
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
db.close();
}
}
// Getting single contact
Contact Get_Contact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS,
new String[] { KEY_ID, KEY_Tittle, KEY_Description, KEY_Price,
KEY_Counter, KEY_Image }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(cursor.getString(0), cursor.getString(1),
cursor.getString(2), cursor.getString(4), cursor.getString(5));
// return contact
cursor.close();
db.close();
return contact;
}
public boolean somethingExists(String x) {
Cursor cursor = db.rawQuery("select * from " + TABLE_CONTACTS
+ " where name like '%" + x + "%'", null);
boolean exists = (cursor.getCount() > 0);
Log.e("Databaseeeeeeeee", String.valueOf(cursor));
cursor.close();
return exists;
}
public ArrayList<Contact> Get_Contacts() {
try {
contact_list.clear();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setTitle(cursor.getString(1));
contact.setDescription(cursor.getString(2));
contact.setPrice(cursor.getString(3));
contact.setCounter(cursor.getString(4));
contact.setImage(cursor.getString(5));
contact_list.add(contact);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return contact_list;
} catch (Exception e) {
// TODO: handle exception
Log.e("all_contact", "" + e);
}
return contact_list;
}
public int getProfilesCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int cnt = cursor.getCount();
cursor.close();
return cnt;
}
}
SQLAdapter.java code
public class StradaSQLAdapter extends BaseAdapter {
Activity activity;
int layoutResourceId;
Contact user;
ArrayList<Contact> data = new ArrayList<Contact>();
public ImageLoader imageLoader;
UserHolder holder = null;
public int itemSelected = 0;
public StradaSQLAdapter(Activity act, int layoutResourceId,
ArrayList<Contact> data) {
this.layoutResourceId = layoutResourceId;
this.activity = act;
this.data = data;
imageLoader = new ImageLoader(act.getApplicationContext());
notifyDataSetChanged();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater inflater = LayoutInflater.from(activity);
holder = new UserHolder();
row = inflater.inflate(layoutResourceId, parent, false);
holder.Title = (TextView) row.findViewById(R.id.smalltitle1);
holder.counter = (TextView) row.findViewById(R.id.smallCounter1);
holder.dbcounter = (TextView) row
.findViewById(R.id.DBSliderCounter);
holder.Description = (TextView) row.findViewById(R.id.smallDesc1);
holder.layout = (RelativeLayout) row
.findViewById(R.id.DBSlideLayout);
holder.layoutmain = (RelativeLayout) row
.findViewById(R.id.DBSlideLayoutMain);
holder.Price = (TextView) row.findViewById(R.id.smallPrice1);
holder.pt = (ImageView) row.findViewById(R.id.smallthumb1);
holder.close = (ImageView) row.findViewById(R.id.DBSliderClose);
holder.c_minus = (ImageView) row.findViewById(R.id.counter_minus);
holder.c_plus = (ImageView) row.findViewById(R.id.counter_plus);
row.setTag(holder);
} else {
holder = (UserHolder) row.getTag();
}
user = data.get(position);
holder.Title.setText(user.getTitle());
holder.Description.setText(user.getDescription());
holder.Price.setText(user.getPrice() + " GEL");
holder.counter.setText(user.getCounter());
holder.dbcounter.setText(user.getCounter());
Log.e("image Url is........", data.get(position).toString());
imageLoader.DisplayImage(user.getImage(), holder.pt);
return row;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public class UserHolder {
public TextView Price, counter, Description, Title, dbcounter;
public ImageView pt,close,c_plus,c_minus;
public RelativeLayout layout, layoutmain;
}
}
and Main java code
public class StradaChartFragments extends Fragment {
public static ListView list;
ArrayList<Contact> contact_data = new ArrayList<Contact>();
StradaSQLAdapter cAdapter;
private DatabaseHandler dbHelper;
UserHolder holder;
private RelativeLayout.LayoutParams layoutParams;
private ArrayList<Contact> contact_array_from_db;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.strada_chart_fragment,
container, false);
dbHelper = new DatabaseHandler(getActivity());
list = (ListView) rootView.findViewById(R.id.chart_listview);
cAdapter = new StradaSQLAdapter(getActivity(),
R.layout.listview_row_db, contact_data);
contact_array_from_db = dbHelper.Get_Contacts();
Set_Referash_Data();
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
final int position, long id) {
holder = (UserHolder) view.getTag();
layoutParams = (RelativeLayout.LayoutParams) holder.layoutmain
.getLayoutParams();
if (holder.layout.getVisibility() != View.VISIBLE) {
ValueAnimator varl = ValueAnimator.ofInt(0, -170);
varl.setDuration(1000);
varl.addUpdateListener(new AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
layoutParams.setMargins(
(Integer) animation.getAnimatedValue(), 0,
0, 0);
holder.layoutmain.setLayoutParams(layoutParams);
}
});
varl.start();
holder.layout.setVisibility(View.VISIBLE);
}
holder.close.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
ValueAnimator var2 = ValueAnimator.ofInt(-170, 0);
var2.setDuration(1000);
var2.addUpdateListener(new AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(
ValueAnimator animation) {
dbHelper.deleteUser(contact_array_from_db.get(position).getTitle());
if (contact_data.size() > 0)
contact_data.remove(position);
layoutParams.setMargins(0, 0,
(Integer) animation.getAnimatedValue(),
0);
holder.layoutmain.setLayoutParams(layoutParams);
holder.layout.setVisibility(View.INVISIBLE);
}
});
var2.start();
}
});
}
});
return rootView;
}
public void Set_Referash_Data() {
contact_data.clear();
for (int i = 0; i < contact_array_from_db.size(); i++) {
String title = contact_array_from_db.get(i).getTitle();
String Description = contact_array_from_db.get(i).getDescription();
String Price = contact_array_from_db.get(i).getPrice();
String Counter = contact_array_from_db.get(i).getCounter();
String image = contact_array_from_db.get(i).getImage();
Contact cnt = new Contact();
cnt.setTitle(title);
cnt.setDescription(Description);
cnt.setPrice(Price);
cnt.setCounter(Counter);
cnt.setImage(image);
contact_data.add(cnt);
}
dbHelper.close();
list.setAdapter(cAdapter);
Log.e("Adapter issss ...", String.valueOf(cAdapter));
}
}
i can remove item in database ,but listview not updated . what am i doing wrong ? if anyone knows solution help me
thanks
Under your method dbHelper.deleteUser add this code:
contact_data.remove(position);
To function in addition to deleting it from the database also have to delete the array of objects that you sent to adapter.
EDIT:
Add one remove method in your adapter for you can remove object. Code:
Adapter:
public void removeObject (int position) {
this.data.remove(position);
}
Activity:
Change:
contact_data.remove(position);
to:
cAdapter.removeObject(position);
cAdapter.notifyDataSetChanged();
EDIT 2:
Just delete all the objects from ArrayList.
contact_data.clear();
or in your adapter
data.clear();
I have here my code. Data on the database are filtered by the title, how can i filter data by title or author? I think it is on these lines of codes on Catalogue.java:
dataAdapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return dbHelper.fetchCollectionsByTitle(constraint.toString());
Here are my codes:
Catalogue.java
package com.cvsu.catalogue.db;
import com.cvsu.catalogue.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FilterQueryProvider;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
//import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
#SuppressLint("NewApi")
public class Catalogue extends Activity {
private CollectionsDbAdapter dbHelper;
private SimpleCursorAdapter dataAdapter;
public final static String TITLE_EXTRA = "com.cvsu.catalogue.db._TITLE";
public final static String AUTHOR_EXTRA = "com.cvsu.catalogue.db._AUTHOR";
public final static String LOCATION_EXTRA = "com.cvsu.catalogue.db._LOCATION";
public final static String CALLNUMBER_EXTRA = "com.cvsu.catalogue.db._CALLNUMBER";
public final static String PUBLISHER_EXTRA = "com.cvsu.catalogue.db._PUBLISHER";
public final static String DATEPUBLISHED_EXTRA = "com.cvsu.catalogue.db._DATEPUBLISHED";
public final static String DESCRIPTION_EXTRA = "com.cvsu.catalogue.db._DESCRIPTION";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.catalogue_title);
dbHelper = new CollectionsDbAdapter(this);
dbHelper.open();
//Generate ListView from SQLite Database
displayListView();
}
private void displayListView() {
Cursor cursor = dbHelper.fetchAllCollections();
// The desired columns to be bound
String[] columns = new String[] {
CollectionsDbAdapter.KEY_TITLE,
CollectionsDbAdapter.KEY_AUTHOR,
CollectionsDbAdapter.KEY_LOCATION,
CollectionsDbAdapter.KEY_CALLNUMBER,
CollectionsDbAdapter.KEY_PUBLISHER,
CollectionsDbAdapter.KEY_DATEPUBLISHED,
CollectionsDbAdapter.KEY_DESCRIPTION
};
// the XML defined views which the data will be bound to
int[] to = new int[] {
R.id.txtTitle,
R.id.txtAuthor,
//R.id.location,
//R.id.callnumber,
//R.id.publisher,
//R.id.datepublished,
//R.id.description,
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(
this, R.layout.book_info_title,
cursor,
columns,
to,
0);
final ListView listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listview, View view,
int position, long id ) {
// Get the cursor, positioned to the corresponding row in the result set
/*Cursor cursor = (Cursor) listView.getItemAtPosition(position);
// Get the state's capital from this row in the database.
String bookTitle =
cursor.getString(cursor.getColumnIndexOrThrow("title"));
Toast.makeText(getApplicationContext(),
bookTitle, Toast.LENGTH_SHORT).show();*/
Intent i = new Intent (CatalogueTitle.this, BookInfoPage.class);
i.putExtra(TITLE_EXTRA, String.valueOf(id));
i.putExtra(AUTHOR_EXTRA, String.valueOf(id));
i.putExtra(LOCATION_EXTRA, String.valueOf(id));
i.putExtra(CALLNUMBER_EXTRA, String.valueOf(id));
i.putExtra(PUBLISHER_EXTRA, String.valueOf(id));
i.putExtra(DATEPUBLISHED_EXTRA, String.valueOf(id));
i.putExtra(DESCRIPTION_EXTRA, String.valueOf(id));
startActivity(i);
}
});
EditText myFilter = (EditText) findViewById(R.id.myFilter);
myFilter.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
dataAdapter.getFilter().filter(s.toString());
}
});
dataAdapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return dbHelper.fetchCollectionsByTitle(constraint.toString());
}
});
}
public static void main(String[] args) {
}
}
Collections.Java
package com.cvsu.catalogue.db;
public class Collections {
String title = null;
String author = null;
String location = null;
String callnumber = null;
String publisher = null;
String datepublished = null;
String description = null;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getCallNumber() {
return callnumber;
}
public void setCallNumber(String callnumber) {
this.callnumber = callnumber;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public String getDatePublished() {
return datepublished;
}
public void setDatePublished(String datepublished) {
this.datepublished = datepublished;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
CollectionsDbAdapter.java
package com.cvsu.catalogue.db;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class CollectionsDbAdapter {
public static final String KEY_ROWID = "_id";
public static final String KEY_TITLE = "title";
public static final String KEY_AUTHOR = "author";
public static final String KEY_LOCATION = "location";
public static final String KEY_CALLNUMBER = "callnumber";
public static final String KEY_PUBLISHER = "publisher";
public static final String KEY_DATEPUBLISHED = "datepublished";
public static final String KEY_DESCRIPTION = "description";
private static final String TAG = "CollectionsDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static final String DATABASE_NAME = "LibraryCollections";
private static final String SQLITE_TABLE = "Collections";
private static final int DATABASE_VERSION = 1;
private final Context mCtx;
private static final String DATABASE_CREATE =
"CREATE TABLE if not exists " + SQLITE_TABLE + " (" +
KEY_ROWID + " integer PRIMARY KEY autoincrement," +
KEY_TITLE + "," +
KEY_AUTHOR + "," +
KEY_LOCATION + "," +
KEY_CALLNUMBER + "," +
KEY_PUBLISHER + "," +
KEY_DATEPUBLISHED + "," +
KEY_DESCRIPTION + "," +
" UNIQUE (" + KEY_CALLNUMBER +"));";
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.w(TAG, DATABASE_CREATE);
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + SQLITE_TABLE);
onCreate(db);
}
}
public CollectionsDbAdapter(Context ctx) {
this.mCtx = ctx;
}
public CollectionsDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
if (mDbHelper != null) {
mDbHelper.close();
}
}
public long createCollections(String title, String author,
String location, String callnumber, String publisher, String datepublished, String description) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_TITLE, title);
initialValues.put(KEY_AUTHOR, author);
initialValues.put(KEY_LOCATION, location);
initialValues.put(KEY_CALLNUMBER, callnumber);
initialValues.put(KEY_PUBLISHER, publisher);
initialValues.put(KEY_DATEPUBLISHED, datepublished);
initialValues.put(KEY_DESCRIPTION, description);
return mDb.insert(SQLITE_TABLE, null, initialValues);
}
public Cursor fetchCollectionsByTitle(String inputText) throws SQLException {
Log.w(TAG, inputText);
Cursor mCursor = null;
if (inputText == null || inputText.length () == 0) {
mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_TITLE, KEY_AUTHOR, KEY_LOCATION, KEY_CALLNUMBER, KEY_PUBLISHER, KEY_DATEPUBLISHED, KEY_DESCRIPTION},
null, null, null, null, null);
}
else {
mCursor = mDb.query(true, SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_TITLE, KEY_AUTHOR, KEY_LOCATION, KEY_CALLNUMBER, KEY_PUBLISHER, KEY_DATEPUBLISHED, KEY_DESCRIPTION},
KEY_TITLE + " like '%" + inputText + "%'", null,
null, null, null, null);
}
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public Cursor fetchCollectionsByAuthor(String inputText) throws SQLException {
Log.w(TAG, inputText);
Cursor mCursor = null;
if (inputText == null || inputText.length () == 0) {
mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_TITLE, KEY_AUTHOR, KEY_LOCATION, KEY_CALLNUMBER, KEY_PUBLISHER, KEY_DATEPUBLISHED, KEY_DESCRIPTION},
null, null, null, null, null);
}
else {
mCursor = mDb.query(true, SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_TITLE, KEY_AUTHOR, KEY_LOCATION, KEY_CALLNUMBER, KEY_PUBLISHER, KEY_DATEPUBLISHED, KEY_DESCRIPTION},
KEY_AUTHOR + " like '%" + inputText + "%'", null,
null, null, null, null);
}
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public Cursor fetchAllCollections() {
Cursor mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_TITLE, KEY_AUTHOR, KEY_LOCATION, KEY_CALLNUMBER, KEY_PUBLISHER, KEY_DATEPUBLISHED, KEY_DESCRIPTION},
null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
}
#Override
public Cursor runQuery(CharSequence constraint) {
Cursor cur = null;
database.openDataBase();
if(constraint!=null){
cur = database.selectDataWithConstrain(constraint.toString());
}
return cur;
}
using this constarint write a query in your Database Class and get the data required either title or author
public Cursor selectDataWithConstrain(String c) {
// TODO Auto-generated method stub
Cursor cursor = myDataBase.rawQuery("SELECT * FROM tbl_xxx WHERE title LIKE '%"+c+"%'", null);
return cursor;
}
public Cursor fetchdatabyfilter(String inputText, String filtercolumn) throws SQLException {
Cursor row = null;
String query = "SELECT * FROM " + dbTable;
if (inputText == null || inputText.length() == 0 ) {
row = sqlDb.rawQuery(query, null);
} else {
query = "SELECT * FROM " + dbTable + " WHERE " + filtercolumn + " like '%" + inputText + "%' ";
row = sqlDb.rawQuery(query, null);
}
if (row != null)
{
row.moveToFirst();
}
return row;
}
mainactivity:
adapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return db.fetchdatabyfilter(constraint.toString(),"title" );
}
});