How to implement a contentobserver specifically for contacts - java

I am looking a way to handle this case when I would expect some service gets a notificaction when the contact database changed... but I dont find an example how to implement this class(for example a handler in this case would be some Action?) and how do I find the Uri for the contacts' db ?
public class ContactContentObserver : ContentObserver
{
public Android.Content.Context _Context { get; set; }
public Android.Net.Uri GetCurrentContactData(Android.Net.Uri uri) =>
Android.Net.Uri.WithAppendedPath(uri, "data");
public ContactContentObserver(Handler handler) : base(handler)
{
}
public ContactContentObserver(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer)
{
}
public override void OnChange(bool selfChange, Android.Net.Uri uri)
{
if(uri.Path.Contains(ContactsContract.AuthorityUri.Path))
{
// Android.Database
// Android.App.Application.Context.
string[] queryColumns =
{
IPhoneLookupColumns.ContactId,
IPhoneLookupColumns.DataId,
IPhoneLookupColumns.Number,
CommonDataKinds.StructuredName.DisplayName,
CommonDataKinds.StructuredName.InterfaceConsts.ContactLastUpdatedTimestamp
};
Dictionary<string, string> values = new Dictionary<string, string>();
Android.Net.Uri newUri = GetCurrentContactData(uri);
ICursor? cursor =_Context.ContentResolver.Query(newUri,queryColumns,null,null,null);
int cols = cursor.GetColumnNames().Length;
Dictionary<string, ContactQueryResult> contactQueryResult = new Dictionary<string, ContactQueryResult>();
for (int row=0;row<cursor.Count;row++)
{
for(int col=0;col<cols;col++)
{
string val = cursor.GetString(col);
values.Add(cursor.GetColumnName(col), val);
}
int.TryParse(values[IPhoneLookupColumns.ContactId], out int contactId);
int.TryParse(values[IPhoneLookupColumns.DataId], out int dataId);
DateTime dateModified = DateTime.MinValue;
bool parsed =DateTime.TryParse(values[CommonDataKinds.StructuredName.InterfaceConsts.ContactLastUpdatedTimestamp], out dateModified);
if (values[IPhoneLookupColumns.Number] is not null or "")
{
string phone = values[IPhoneLookupColumns.Number];
var val = new ContactQueryResult
{
ContactId = contactId,
ContactLastUpdatedTimestamp = parsed ? dateModified : null,
DataId = dataId,
DisplayName = values[CommonDataKinds.StructuredName.DisplayName],
PhoneNumber = phone
};
contactQueryResult.Add(phone, val);
}
values.Clear();
}
}
base.OnChange(selfChange, uri);
}
}```

Related

How to solve 'Cannot retrieve length of file, path (OS Error: No such file or directory, errno = 2) ' in flutter

I am building a simple music player app in which I want to fetch all songs available on the users device. I am doing this with my custom method in java
private static List<Map<String, String>> getAllSongs(Context context) {
List<Map<String, String>> songs = new ArrayList<>();
// Set up query to get all audio files
String[] projection = new String[] {
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.ALBUM,
MediaStore.Audio.Media.DURATION,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.ALBUM_ID
};
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
String sortOrder = MediaStore.Audio.Media.TITLE + " ASC";
// Execute query
Cursor cursor = context.getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
projection,
selection,
null,
sortOrder
);
// Extract metadata from query result
if (cursor != null && cursor.moveToFirst()) {
int idColumnIndex = cursor.getColumnIndex(MediaStore.Audio.Media._ID);
int titleColumnIndex = cursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
int artistColumnIndex = cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
int albumColumnIndex = cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM);
int durationColumnIndex = cursor.getColumnIndex(MediaStore.Audio.Media.DURATION);
int pathColumnIndex = cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
int albumIdColumnIndex = cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID);
do {
Map<String, String> song = new HashMap<>();
song.put("id", cursor.getString(idColumnIndex));
song.put("title", cursor.getString(titleColumnIndex));
song.put("artist", cursor.getString(artistColumnIndex));
song.put("album", cursor.getString(albumColumnIndex));
song.put("duration", cursor.getString(durationColumnIndex));
song.put("path", cursor.getString(pathColumnIndex));
long albumId = cursor.getLong(albumIdColumnIndex);
Uri albumArtUri = Uri.withAppendedPath(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, Long.toString(albumId));
song.put("albumArt", albumArtUri.toString());
songs.add(song);
} while (cursor.moveToNext());
cursor.close();
}
return songs;
}
This is then handled in flutter by ->
class Song {
String id;
String title;
String artist;
String album;
String path;
String albumArt;
Song(
{required this.id,
required this.title,
required this.artist,
required this.album,
required this.path,
required this.albumArt});
}
class MusicService {
static const MethodChannel _channel = const MethodChannel('com.mybea.ah');
static Future<List<Song>> getAllSongs() async {
List<Song> songs = [];
try {
final List<dynamic> result = await _channel.invokeMethod('getAllSongs');
if (result.isNotEmpty) {
for (int i = 0; i < result.length; i++) {
songs.add(Song(
id: result[i]['id'],
title: result[i]['title'],
artist: result[i]['artist'],
album: result[i]['album'],
path: result[i]['path'],
albumArt: result[i]['albumArt'],
));
}
}
} on PlatformException catch (e) {
print("Failed to get all songs: '${e.message}'.");
}
return songs;
}
}
When I fetch the songs from the method all is fetched properly but when I try to display the artwork I get the following error->
════════ Exception caught by image resource service
════════════════════════════ Cannot retrieve length of file, path =
'content://media/external/audio/albums/89' (OS Error: No such file or
directory, errno = 2)
This is the code where I try to use the method ->
Future<void> _loadSongs() async {
if (await Permission.storage.request().isGranted) {
List<Song> songs = await MusicService.getAllSongs();
setState(() {
_songs = songs;
} else {
return;
}
}
_songs.length == 0
? Center(
child: Text("No Songs Found"),
)
: ListView.builder(
itemCount: _songs.length,
itemBuilder: (context, index) {
Song song = _songs[index];
return ListTile(
onTap: () {
debugPrint(song.path);
},
leading: CircleAvatar(
backgroundImage: FileImage(File(song.albumArt)),
),
title: Text(song.title),
subtitle: Text(song.artist),
trailing: Icon(Icons.play_arrow),
);
},
),
I tried displaying the image by Image.file() and Image.network() but nothing seemed to work and gave the same error.
Please Help

compress and upload multiple files with progress using RxWorker

I try to upload multiple images to the server and before that, I want to compress my images. for compressing part I use AdvancedLuban Library in my project to compress selected images of users and then for uploading part I use Retrofit in RxJava way. I do all in my presenter class and all of this works properly. My problem is I want to do all of this in my UploadWorker class which is inherited from RxWorker and while doing uploading show progress in the notification.
The code I wrote does not work properly and notification progress did not update correctly.
Here is my UploadWorker.class
public class UploadWorker extends RxWorker {
private static final String TAG = UploadWorker.class.getSimpleName();
public static final String KEY_STRING_DATA = "string_data";
private static final int COMPRESS_MAX_SIZE = 200;
private static final int PROGRESS_MAX = 100;
private Context context;
private FileUploader uploader;
public UploadWorker(#NonNull Context context, #NonNull WorkerParameters workerParams) {
super(context, workerParams);
this.context = context;
ApiService apiService = ServiceBuilder.buildService(ApiService.class);
uploader = new FileUploader(apiService);
}
#NonNull
#Override
public Single<Result> createWork() {
Data data = getInputData();
String strData = data.getString(KEY_STRING_DATA);
List<String> stringList = deserializeFromJson(strData);
List<File> files = new ArrayList<>();
for (String path : stringList) {
File f = new File(path);
files.add(f);
}
return Single.fromObservable(Luban.compress(context,files)
.setMaxSize(COMPRESS_MAX_SIZE)
.putGear(Luban.CUSTOM_GEAR)
.setCompressFormat(Bitmap.CompressFormat.JPEG)
.asListObservable()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.map(new Function<List<File>, ArrayList<String>>() {
#Override
public ArrayList<String> apply(List<File> files) throws Exception {
ArrayList<String> filListPath = new ArrayList<>();
for (File file:files) {
filListPath.add(file.getAbsolutePath());
}
return filListPath ;
}
})
.map(new Function<ArrayList<String>, Disposable>() {
#Override
public Disposable apply(ArrayList<String> strings) throws Exception {
HashMap<String, RequestBody> map = new HashMap<>();
return getUploadObserver(map,strings);
}
}).map(new Function<Disposable, Result>() {
#Override
public Result apply(Disposable disposable) throws Exception {
return Result.success();
}
})
);
}
private Disposable getUploadObserver(HashMap<String, RequestBody> map, ArrayList<String> files) {
return uploader.uploadMultiImage(map, files)
.subscribeOn(Schedulers.computation())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<Double>() {
#Override
public void accept(Double progress) throws Exception {
notifyUpload((int) (100 * progress));
Log.d(TAG, "accept: " + (int) (100 * progress));
}
});
}
public void notifyUpload(int progress) {
NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(context);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, Config.NOTIFICATION_CHANNEL);
builder.setSmallIcon(R.drawable.ic_notification_icon)
.setContentTitle("Upload")
.setContentText("Uploading in progress")
.setPriority(NotificationCompat.PRIORITY_LOW)
.setAutoCancel(true);
if (progress < PROGRESS_MAX) {
builder.setProgress(PROGRESS_MAX, progress, false);
}else {
builder.setContentText("Upload complete")
.setProgress(0,0,false);
}
notificationManagerCompat.notify(200, builder.build());
}
public static List<String> deserializeFromJson(String jsonString){
Gson gson = new Gson();
Type listOf = new TypeToken<ArrayList<String>>() {}.getType();
return gson.fromJson(jsonString,listOf);
}
}
FileUploader.class
public class FileUploader implements FileUploaderContract{
private final ApiService service;
private static final String TAG = FileUploaderModel.class.getSimpleName();
public FileUploaderModel(ApiService service) {
this.service = service;
}
#Override
public Flowable<Double> uploadMultiImage(HashMap<String,RequestBody> map, ArrayList<String> filePaths) {
return Flowable.create(new FlowableOnSubscribe<Double>() {
#Override
public void subscribe(FlowableEmitter<Double> emitter) throws Exception {
try {
List<MultipartBody.Part> myPart = new ArrayList<>();
for (String path:filePaths) {
myPart.add(createMultipartBody(path, emitter));
}
ResponseBody response = service.postMultipleImage(map,myPart).blockingGet();
Log.d(TAG, "subscribe: " + response);
emitter.onComplete();
} catch (Exception e) {
emitter.tryOnError(e);
}
}
}, BackpressureStrategy.LATEST);
}
#NonNull
private RequestBody createPartFromString(String descriptionString) {
return RequestBody.create(MultipartBody.FORM, descriptionString);
}
private MultipartBody.Part createMultipartBody(String filePath, FlowableEmitter<Double> emitter) {
File file = new File(filePath);
return MultipartBody.Part.createFormData("image", file.getName(), createCountingRequestBody(file, emitter));
}
private RequestBody createCountingRequestBody(File file, FlowableEmitter<Double> emitter) {
RequestBody requestBody = createRequestBody(file);
return new CountingRequestBody(requestBody, (bytesWritten, contentLength) -> {
double progress = (1.0 * bytesWritten) / contentLength;
emitter.onNext(progress);
});
}
}
And call my UploadWorker in my MainActivity like below
String strData = serializeToJson(mAdapter.getImageList());
Data data = new Data.Builder()
.putString(UploadWorker.KEY_STRING_DATA,strData)
.build();
WorkRequest mRequestWork = new OneTimeWorkRequest.Builder(UploadWorker.class)
.setInitialDelay(1, TimeUnit.SECONDS)
.setInputData(data)
.build();
WorkManager.getInstance(getContext()).enqueue(mRequestWork)

How to get paths of folders that has image or video

I want to create an android gallery app .
How to scan and get paths of folders that includes photos or videos .
I used this code and worked . but when i compare it with Quickpic Gallery in play store , i see the count of folders in my app is less than Quickpic folders
Do you see any problem in this code ?
Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
Cursor cursor = ba.context.getContentResolver().query(uri, null, null,
null, MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME);
if (cursor != null) {
cursor.moveToFirst();
int data = cursor
.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
int displayName = cursor
.getColumnIndex(MediaStore.Images.ImageColumns.DISPLAY_NAME);
imageFolders = new HashMap<>();
do {
String imageAddress = cursor.getString(data);
String imageName = cursor.getString(displayName);
String folderAddress = imageAddress.substring(0,
imageAddress.lastIndexOf(imageName) - 1);
if (!imageFolders.containsKey(folderAddress)) {
imageFolders.put(folderAddress, imageAddress);
}
} while (cursor.moveToNext());
for (String str : imageFolders.keySet()) {
ba.raiseEventFromDifferentThread(
null,
null,
0,
"result",
true,
new Object[] { String.format("%s", str),
String.format("%s", imageFolders.get(str)) });
}
}
this way you can find all video and image parents.
ArrayList<String> allFolder;
HashMap<String, ArrayList<String>> listImageByFolder;
ArrayList<String> allVideoFolder;
HashMap<String, ArrayList<String>> listVideoByFolder;
find all images folder path
private void getImageFolderList() {
String[] projection = new String[] { MediaStore.Images.Media.DATA,
MediaStore.Images.Media._ID,
MediaStore.Images.Media.BUCKET_DISPLAY_NAME,
MediaStore.Images.Media.DATE_TAKEN };
Uri images = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
final String orderBy = MediaStore.Images.Media.DATE_TAKEN;
Cursor cur = getContentResolver().query(images, projection, // Which
// columns
// to return
null, // Which rows to return (all rows)
null, // Selection arguments (none)
orderBy + " DESC" // Ordering
);
ArrayList<String> imagePath;
if (cur.moveToFirst()) {
String bucket, date;
int bucketColumn = cur.getColumnIndex(MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
int dateColumn = cur.getColumnIndex(MediaStore.Images.Media.DATE_TAKEN);
do {
bucket = cur.getString(bucketColumn);
date = cur.getString(dateColumn);
if (!allFolder.contains(bucket)) {
allFolder.add(bucket);
}
imagePath = listImageByFolder.get(bucket);
if (imagePath == null) {
imagePath = new ArrayList<String>();
}
imagePath.add(cur.getString(cur
.getColumnIndex(MediaStore.Images.Media.DATA)));
listImageByFolder.put(bucket, imagePath);
} while (cur.moveToNext());
}
}
find all videos folder path
private void getVideoFolderList() {
String[] projection = new String[] { MediaStore.Video.Media.DATA,
MediaStore.Video.Media._ID,
MediaStore.Video.Media.BUCKET_DISPLAY_NAME,
MediaStore.Video.Media.DATE_TAKEN };
Uri images = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
final String orderBy = MediaStore.Video.Media.DATE_TAKEN;
Cursor cur = getContentResolver().query(images, projection, // Which
// columns
// to return
null, // Which rows to return (all rows)
null, // Selection arguments (none)
orderBy + " DESC" // Ordering
);
ArrayList<String> imagePath;
if (cur.moveToFirst()) {
String bucket, date;
int bucketColumn = cur.getColumnIndex(MediaStore.Video.Media.BUCKET_DISPLAY_NAME);
int dateColumn = cur.getColumnIndex(MediaStore.Video.Media.DATE_TAKEN);
do {
bucket = cur.getString(bucketColumn);
date = cur.getString(dateColumn);
if (!allVideoFolder.contains(bucket)) {
allVideoFolder.add(bucket);
}
imagePath = listVideoByFolder.get(bucket);
if (imagePath == null) {
imagePath = new ArrayList<String>();
}
imagePath.add(cur.getString(cur
.getColumnIndex(MediaStore.Images.Media.DATA)));
listVideoByFolder.put(bucket, imagePath);
} while (cur.moveToNext());
}
}
i can see you are trying to get the folder names of all folders containing video files the answer given by #prakash ubhadiya is good an works but for the problem that if the are many of such folders with same name the function will keep only one and ignore the rest, below i have modified his fuction to return not only the folder names but also the folder absolute path in case you will want to use this to get all the video files in that specific folder, i have created a class called floderFacer the holds the folder name and the folder adsolute path, done this way no folders with same names will be ignored below is the class
public class folderFacer {
private String path;
private String folderName;
public folderFacer(){
}
public folderFacer(String path, String folderName) {
this.path = path;
this.folderName = folderName;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getFolderName() {
return folderName;
}
public void setFolderName(String folderName) {
this.folderName = folderName;
}
}
now below is the modified fuction that will return the folder names and paths in a folderFacer object all in an ArrayList<folderFacer>
private ArrayList<folderFacer> getVideoPaths(){
ArrayList<folderFacer> videoFolders = new ArrayList<>();
ArrayList<String> videoPaths = new ArrayList<>();
Uri allVideosuri = android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
String[] projection = { MediaStore.Video.VideoColumns.DATA ,MediaStore.Video.Media.DISPLAY_NAME,
MediaStore.Video.Media.BUCKET_DISPLAY_NAME,MediaStore.Video.Media.BUCKET_ID};
Cursor cursor = getContentResolver().query(allVideosuri, projection, null, null, null);
try {
cursor.moveToFirst();
do{
folderFacer folds = new folderFacer();
String name = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME));
String folder = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.BUCKET_DISPLAY_NAME));
String datapath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA));
String folderpaths = datapath.replace(name,"");
if (!videoPaths.contains(folderpaths)) {
videoPaths.add(folderpaths);
folds.setPath(folderpaths);
folds.setFolderName(folder);
videoFolders.add(folds);
}
}while(cursor.moveToNext());
cursor.close();
} catch (Exception e) {
e.printStackTrace();
}
for(int i = 0;i < videoFolders.size();i++){
Log.d("video folders",videoFolders.get(i).getFolderName()+" and path = "+videoFolders.get(i).getPath());
}
return videoFolders;
}
hope this helps

get mp3 files from path

I'm trying to get mp3 files from a folder path of my system to list it in my listView, but unfortunately there's always the same error. (java.lang.NullPointerException: Attempt to get length of null array)
class Mp3Filter implements FilenameFilter{
public boolean accept(File dir, String name){
return (name.endsWith(".mp3"));
}
}
private static final String SD_PATH = new String(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).toString());
public void searchForSongs() {
ListView listView;
listView = (ListView) findViewById(R.id.listView);
File f = new File(SD_PATH);
try {
if (f.listFiles(new Mp3Filter()).length > 0){
for (File file : f.listFiles(new Mp3Filter())){
list.add(file.getName());
}
}
}
catch(Exception e) {
textView2.setText(""+e);
return;
}
final ArrayAdapter songList = new ArrayAdapter(this, android.R.layout.simple_list_item_1, list);
listView.setAdapter(songList);
}
Here is your solution use the following code to Read the MP3 file from the Specific Folder..
First of all Create 1 Model class as Given Below, to GET and SET Files in list.
AudioModel.class
public class AudioModel {
String aPath;
String aName;
String aAlbum;
String aArtist;
public String getaPath() {
return aPath;
}
public void setaPath(String aPath) {
this.aPath = aPath;
}
public String getaName() {
return aName;
}
public void setaName(String aName) {
this.aName = aName;
}
public String getaAlbum() {
return aAlbum;
}
public void setaAlbum(String aAlbum) {
this.aAlbum = aAlbum;
}
public String getaArtist() {
return aArtist;
}
public void setaArtist(String aArtist) {
this.aArtist = aArtist;
}
}
Now We have our Model Class Now use the below code to Read the all MP3 files from your Folder.
This will return list of all MP3 Files with Music NAME, PATH, ARTIST, ALBUM and if you wants more detail please refer Media.Store.Audio doc..
https://developer.android.com/reference/android/provider/MediaStore.Audio.html
public List<AudioModel> getAllAudioFromDevice(final Context context) {
final List<AudioModel> tempAudioList = new ArrayList<>();
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.Audio.AudioColumns.DATA, MediaStore.Audio.AudioColumns.ALBUM, MediaStore.Audio.ArtistColumns.ARTIST,};
Cursor c = context.getContentResolver().query(uri, projection, MediaStore.Audio.Media.DATA + " like ? ", new String[]{"%yourFolderName%"}, null);
if (c != null) {
while (c.moveToNext()) {
AudioModel audioModel = new AudioModel();
String path = c.getString(0);
String album = c.getString(1);
String artist = c.getString(2);
String name = path.substring(path.lastIndexOf("/") + 1);
audioModel.setaName(name);
audioModel.setaAlbum(album);
audioModel.setaArtist(artist);
audioModel.setaPath(path);
Log.e("Name :" + name, " Album :" + album);
Log.e("Path :" + path, " Artist :" + artist);
tempAudioList.add(audioModel);
}
c.close();
}
return tempAudioList;
}
To Read Files of Specific Folder, use below Query and write your folder name in Query..
Cursor c = context.getContentResolver().query(uri,
projection,
MediaStore.Audio.Media.DATA + " like ? ",
new String[]{"%yourFolderName%"}, // yourFolderName
null);
If you wants All Files of device use below Query..
Cursor c = context.getContentResolver().query(uri,
projection,
null,
null,
null);
Don't forget to add Storage Permission .. enjoy.

change filtration criteriain smartGWT

i am developing a smartGWT app, and i want to filter the listGrid fields , in a way other than the default one , (ie. the default filtration is based on dearching on a contains matching )
to be more spastic ill give an example :
if a filed have 2 values one of them is the word "valid" and the other is the word "invalid" then the filtration works correctly for searching the word invalid but when i want to see "valid" , it will give me all the "valid" and "invalid" words since "invalid" consists of "in"+"valid"
registeredDate = new DataSourceDateField("registrationDate", voc.registeredDate());
registeredDate.setRequired(true);
verificationDate = new DataSourceDateField("lastVerificationDate", voc.verificationDate());
verificationDate.setRequired(true);
the same as every other field
this is how i fill records :
registeredUsersRecords = new ListGridRecord[registeredUsers.length()];
ListGridRecord record = new ListGridRecord();
record.setAttribute(ID, user.getId());
record.setAttribute("firstName", user.getFirstName());
record.setAttribute("lastName", user.getLastName());
record.setAttribute("email", user.getEmail());
record.setAttribute("userMainType", type);
record.setAttribute("isActivated", (user.isActivated())? voc.active(): voc.inActive());
record.setAttribute("country", user.getSelectedCountry().getValue());
record.setAttribute("companyName", user.getCompanyName());
record.setAttribute("registrationDate", user.getRegistrationDate());
record.setAttribute("lastVerificationDate", user.getVerificationDate());
registeredUsersRecords[i] = record;
and then i put them into datasource :
DataSource ds = new DataSource();
ds.setClientOnly(true);
ds.setFields(fName, lName, email, type,typeDetails, status, country, companyName, registeredDate,verificationDate);
for(int i = 0; i< registeredUsersRecords.length; i++){
ds.addData(registeredUsersRecords[i]);
}
registeredUsersListGrid.setDataSource(ds);
registeredUsersListGrid.fetchData();
I think FilterEditorSubmitHandler will solve your problem.
I have already posted a sample code at your last question here date filtering not working in smart gwt.
You have to do some modification in it as shown below:
Note: In the below sample code I have replaced the filter criteria operator from ICONTAINS to STARTS_WITH. Modify it as per your requirement.
--EDIT--
Complete code:
class User {
private int id;
private String firstName;
private Date registrationDate;
public User(int id, String firstName, Date registrationDate) {
this.id = id;
this.firstName = firstName;
this.registrationDate = registrationDate;
}
public int getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public Date getRegistrationDate() {
return registrationDate;
}
}
DateTimeFormat format = DateTimeFormat.getFormat("MM/dd/yyyy");
User[] registeredUsers = new User[] { new User(1, "valid", format.parse("01/20/2014")),
new User(2, "invalid", format.parse("05/20/2013")),
new User(3, "valid", format.parse("02/20/2014")) };
ListGridRecord[] registeredUsersRecords = new ListGridRecord[registeredUsers.length];
for (int i = 0; i < registeredUsers.length; i++) {
User user = registeredUsers[i];
ListGridRecord record = new ListGridRecord();
record.setAttribute("id", user.getId());
record.setAttribute("firstName", user.getFirstName());
record.setAttribute("registrationDate", user.getRegistrationDate());
registeredUsersRecords[i] = record;
}
DataSourceDateField registeredDate = new DataSourceDateField("registrationDate", "Date");
DataSourceTextField firstName = new DataSourceTextField("firstName", "Name");
DataSourceIntegerField id = new DataSourceIntegerField("id", "ID");
id.setRequired(true);
id.setPrimaryKey(true);
id.setHidden(true);
DataSource ds = new DataSource();
ds.setClientOnly(true);
ds.setFields(id, firstName, registeredDate);
for (int i = 0; i < registeredUsersRecords.length; i++) {
ds.addData(registeredUsersRecords[i]);
}
final ListGrid registeredUsersListGrid = new ListGrid();
registeredUsersListGrid.setDataSource(ds);
registeredUsersListGrid.fetchData();
registeredUsersListGrid.setShowFilterEditor(true);
registeredUsersListGrid.addFilterEditorSubmitHandler(new FilterEditorSubmitHandler() {
#Override
public void onFilterEditorSubmit(FilterEditorSubmitEvent event) {
event.cancel();
if (event.getCriteria() != null) {
AdvancedCriteria advancedCriteria = event.getCriteria().asAdvancedCriteria();
// store only single criteria for each field(column)
Map<String, Criterion> criterions = new HashMap<String, Criterion>();
for (final Criterion criterion : advancedCriteria.getCriteria()) {
System.out.println(criterion.getFieldName());
System.out.println(criterion.getValueAsString());
System.out.println(criterion.getOperator());
if (criterion.getOperator() == OperatorId.ICONTAINS) {
Criterion newCritearia = new Criterion(criterion.getFieldName(),
OperatorId.STARTS_WITH, criterion.getValueAsString());
criterions.put(criterion.getFieldName(), newCritearia);
} else {
criterions.put(criterion.getFieldName(), criterion);
}
}
if (criterions.size() > 0) {
AdvancedCriteria filterCriteria = new AdvancedCriteria(OperatorId.AND,
criterions.values().toArray(new Criterion[] {}));
registeredUsersListGrid.fetchData(filterCriteria);
}
}
}
});
Button button = new Button("Clear all filters");
button.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
registeredUsersListGrid.fetchData();
}
});
VLayout layout = new VLayout();
layout.setWidth("200px");
layout.setHeight("200px");
layout.addMember(button);
layout.addMember(registeredUsersListGrid);
layout.draw();

Categories

Resources