How to sort files using datetimestamp - java

I am capturing images, then storing into SD Card and showing in a List, but here i need a small change, still i am getting old on top and latest at bottom, so now i want to show latest picture on the top on the basis of datetimestamp using as a part of file name.
UploadActivity.java code:-
String fileName;
static List <String> ImageList;
/*** Get Images from SDCard ***/
ImageList = getSD();
// ListView and imageAdapter
lstView = (ListView) findViewById(R.id.listView1);
lstView.setAdapter(new ImageAdapter(this));
}
public static List <String> getSD()
{
List <String> it = new ArrayList <String>();
String string = "/mnt/sdcard/Pictures/SamCam/";
f = new File (string+ CameraLauncherActivity.folder+ "/");
files = f.listFiles ();
for (int i = 0; i < files.length; i++)
{
file = files[i];
Log.d("Count",file.getPath());
it.add (file.getPath());
}
return it;
}
public class ImageAdapter extends BaseAdapter
{
private Context context;
public ImageAdapter(Context c)
{
// TODO Auto-generated method stub
context = c;
}
Note: I am using date/timestamp while storing my images into SD Card.
so finally it looks like this:
AU_20140328163947_1_4_X-1-4-006.jpg
and still files listing in below format, like below:
AU_20140328163947_1_4_X-1-4-006.jpg
AU_20140328163948_1_4_X-1-4-007.jpg
AU_20140328163949_1_4_X-1-4-008.jpg
but i want to list files in below format:-
AU_20140328163949_1_4_X-1-4-008.jpg
AU_20140328163948_1_4_X-1-4-007.jpg
AU_20140328163947_1_4_X-1-4-006.jpg
Code to Delete Image in a List:--
// btnDelete
final ImageButton btnDelete = (ImageButton) convertView.findViewById(R.id.btnDelete);
btnDelete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// set title
alertDialogBuilder.setTitle("Delete Image");
// Setting Icon to Dialog
alertDialogBuilder.setIcon(R.drawable.ic_launcher);
// set dialog message
alertDialogBuilder
.setMessage("Are you sure you want to delete this image?")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
// to get fileName
fileName = ImageList.get(position).toString().substring(strPath.lastIndexOf('/')+1, strPath.length());
// to get SD card path (Folders+fileName)
String fileToDelete = Environment.getExternalStorageDirectory().getPath() +"/Pictures/SamCam/" + CameraLauncherActivity.folder+ "/" + fileName;
Log.d("FileToDelete", fileToDelete);
File myFile = new File(fileToDelete);
// if image exists
if(myFile.exists())
// delete image
myFile.delete();
// get position and delete
ImageList.remove(position);
// to refresh the view
((BaseAdapter) lstView.getAdapter()).notifyDataSetChanged();
dialog.cancel();
}
})
.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
// TODO Auto-generated method stub
}
});
return convertView;
}
}

If you getting data in reverse order than you can use reverse loop.
Try below loop
for (int i = files.length-1; i >= 0; i--)
{
file = files[i];
Log.d("Count",file.getPath());
it.add (file.getPath());
}
instead of
for (int i = 0; i < files.length; i++)
{
file = files[i];
Log.d("Count",file.getPath());
it.add (file.getPath());
}
or sort data with particular field
Sort array data before using in for loop and use same loop..
Arrays.sort(files, new Comparator<Object>()
{
public int compare(Object o1, Object o2) {
if (((File)o1).lastModified() > ((File)o2).lastModified()) {
return -1;
} else if (((File)o1).lastModified() < ((File)o2).lastModified()) {
return +1;
} else {
return 0;
}
}
});
for (int i = 0; i < files.length; i++)
{
file = files[i];
Log.d("Count",file.getPath());
it.add (file.getPath());
}

Use MediaStore ContentProvider for this job
Save the image using MediaStore using this method
And you can query the image using this method
Set the order by as MediaStore.Images.Media.DATE_TAKEN

You can use the Collections.sort method in your list adapter to sort the values according to the image file name like:
Collections.sort(ImageList, new Comparator<String>() {
int compare(String obj1, String obj2) {
return obj1.compareTo(obj2);
}
});
compareTo method and also compareToIgnoreCase method, use wichever you think is appropriate, and also, you can experiment with obj1 and obj2, that is, you could swap the condition to:
return obj2.compareTo(obj1);
That way your list will be sorted. Hope that helps!
EDIT:
Since you know that the format is _ and then -.jpg, what you can do is in the comparator split the value from - like:
Collections.sort(ImageList, new Comparator<String>() {
int compare(String obj1, String obj2) {
String[] obj1Arr = obj1.split(-);
String[] obj2Arr = obj2.split(-);
obj1Arr = obj1Arr[1].split("."); // to just get the counter value
obj2Arr = obj2Arr[1].split(".");
return obj1Arr[0].compareTo(obj2Arr[0]);
}
});

Related

Cannot get file in Download directory to delete using File.delete() on android studio

Here is my current code. I am very new to programming and Android Studio. I assumed that there is a stupid logic error somewhere in here but have checked it over (and over, and over) and cannot for the life of me figure out why files will not delete.
The intention is for the bottom bar to come up when an item/items are long clicked and the DEL button will appear and when the user confirms, the file will delete. However, the files will not delete/be removed from the list of items after confirming.
Please help! Thanks
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout1);
}
class TextAdapter extends BaseAdapter{
// String array of items in a directory
private List<String> data = new ArrayList<>();
// Boolean array to store which items are selected in list
private boolean[] selection;
public void setData(List<String> data){
if(data != null){
this.data.clear();
if(data.size() > 0){
this.data.addAll(data);
}
notifyDataSetChanged();
}
}
void setSelection(boolean[] selection){
if(selection != null){
// Creating new array copy
this.selection = new boolean[selection.length];
// Populating new array copy
for (int i = 0; i < selection.length; i++){
this.selection[i] = selection[i];
}
// Notifying that data changed
notifyDataSetChanged();
}
}
#Override
public int getCount() {
return data.size();
}
#Override
public String getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
convertView.setTag(new ViewHolder((TextView) convertView.findViewById(R.id.textItem)));
}
ViewHolder holder = (ViewHolder) convertView.getTag();
final String path = getItem(position);
holder.info.setText(path.substring(path.lastIndexOf('/')+1));
if(selection != null){
if(selection[position]){
holder.info.setBackgroundColor(Color.LTGRAY);
}
else{
holder.info.setBackgroundColor(Color.WHITE);
}
}
return convertView;
}
class ViewHolder{
TextView info;
ViewHolder(TextView info){
this.info = info;
}
}
}
// Checking permissions
private static final int REQUEST_PERMISSIONS = 1234;
// String array storing read/write external storage permission
private static final String[] PERMISSIONS = {
// Requires min SDK version 16
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
// Asking for 2 permissions
private static final int PERMISSIONS_COUNT = 2;
// Return boolean for if permissions will be granted
#SuppressLint("NewApi")
private boolean arePermissionsDenied(){
int p = 0;
while (p < PERMISSIONS_COUNT){
// If permission is not granted
if(checkSelfPermission(PERMISSIONS[p]) != PackageManager.PERMISSION_GRANTED){
return true;
}
p++;
}
return false;
}
// Flag to check if file manager is intialized
private boolean isFileManagerInit = false;
// Stores which items are selected in manager for modifying/opening
private boolean[] selection;
private File[] files;
private List<String>filesList;
private int filesFoundCount;
// OnResume
#Override
protected void onResume(){
super.onResume();
// If build is Marshmellow or higher, we have to ask for permissions
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && arePermissionsDenied()) {
// Requesting for permissions
requestPermissions(PERMISSIONS, REQUEST_PERMISSIONS);
return;
}
// Checking if File Manager has been initialized. If not, initialize
if(!isFileManagerInit){
// Setting default folder
final String rootPath = String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS));
final File dir = new File(rootPath);
// Creating file array
files = dir.listFiles();
// Displaying current path
final TextView pathOutput = findViewById(R.id.pathOutput);
// Setting pathOutput text to rootPath
pathOutput.setText(rootPath.substring(rootPath.lastIndexOf('/')+1));
// Number of files
filesFoundCount = files.length;
// Creating List elements and populating
final ListView listView = findViewById(R.id.listView);
final TextAdapter textAdapter1 = new TextAdapter();
listView.setAdapter(textAdapter1);
filesList = new ArrayList<>();
for(int i = 0; i < filesFoundCount; i++){
filesList.add(String.valueOf(files[i].getAbsolutePath()));
}
textAdapter1.setData(filesList);
// Allocating memory for array
selection = new boolean[files.length];
// To set item as selected
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
// If unselected, select it
selection[position] = !selection[position];
// If selected, unselect it
textAdapter1.setSelection(selection);
boolean isAtLeastOneSelected = false;
// Checking if elements are selected
for(int i = 0; i < selection.length; i++){
if(selection[i]){
isAtLeastOneSelected = true;
break;
}
}
// If there are selections made, pull up the buttons on bottom
if(isAtLeastOneSelected){
findViewById(R.id.bottomBar).setVisibility(View.VISIBLE);
}
// If there are no selections, then hide bottom bar
else{
findViewById(R.id.bottomBar).setVisibility(View.GONE);
}
return false;
}
});
final Button b1 = findViewById(R.id.b1);
final Button b2 = findViewById(R.id.b2);
final Button b3 = findViewById(R.id.b3);
final Button b4 = findViewById(R.id.b4);
final Button b5 = findViewById(R.id.b5);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder deleteDialog = new AlertDialog.Builder(MainActivity.this);
deleteDialog.setTitle("Delete");
deleteDialog.setMessage("Are you sure you want to delete this file/folder?");
deleteDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
// If user wants to delete
public void onClick(DialogInterface dialog, int which) {
for(int i = 0; i < files.length; i++){
if(selection[i]){
deleteFileOrFolder(files[i]);
selection[i]=false;
}
}
files = dir.listFiles();
filesFoundCount = files.length;
filesList.clear();
for(int i = 0; i < filesFoundCount; i++){
filesList.add(String.valueOf(files[i].getAbsolutePath()));
}
textAdapter1.setData(filesList);
}
});
deleteDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
deleteDialog.show();
}
});
// Setting isFileManagerInit to true
isFileManagerInit = true;
}
}
// Method that will delete file or folder
private void deleteFileOrFolder(File fileOrFolder){
// Check if file or directory
// If folder
if(fileOrFolder.isDirectory()){
// If folder is empty
if(fileOrFolder.list().length == 0){
fileOrFolder.delete();
}
// Delete every file in the folder
else{
String files[] = fileOrFolder.list();
for(String temp:files){
File fileToDelete = new File(fileOrFolder, temp);
deleteFileOrFolder(fileToDelete);
}
// Deleting folder itself
if(fileOrFolder.list().length == 0){
fileOrFolder.delete();
}
}
}
// If just a file
else{
fileOrFolder.delete();
}
}
// Checking if the user granted permissions
#SuppressLint("NewApi")
#Override
public void onRequestPermissionsResult(final int requestCode, final String[] permissions,
final int[] grantResults){
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// If requestCode equal to request permissions and are not null
if(requestCode == REQUEST_PERMISSIONS && grantResults.length>0){
// If permissions denied, clear app data to continue asking user for permissions
if(arePermissionsDenied() == true){
// Requires 19 or higher, but will not be called anyway if that is the case, ignore warnings
((ActivityManager) Objects.requireNonNull(this.getSystemService(ACTIVITY_SERVICE))).clearApplicationUserData();
recreate();
}
else{
onResume();
}
}
}
}
This array declaration is invalid:
String files[] = fileOrFolder.list();
Don't over complicate the deleteFileOrFolder() method. Try it like this:
private boolean deleteFileOrFolder(File fileOrFolder){
File[] files = fileOrFolder.listFiles();
if (files != null) {
for (File file : files) {
deleteFileOrFolder(file);
}
}
return fileOrFolder.delete();
}

adding functionality to back key in android to go to previous folder location in a file manager

I know this has been discussed so many times but really I am not able to figure it out. I am so sorry for asking it again. I am making android file manager. I am showing the files and folders in a listview. I want to add functionality to "back" key. Currently pressing back key at any time results in exit from the app. I want it to go to the previous folder if any or otherwise exit the app. I was trying onBackPressed() method but couldn't figure out what should be written there. Please help me.
Here is my MainActivity.java file :
public class MainActivity extends ListActivity {
private ArrayList<String> item = null;
private ArrayList<String> path = null;
private String root="/";
private TextView myPath;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); /**super keyword in java is a reference variable that
is used to refer immediate parent class object. */
setContentView(R.layout.activity_main);
myPath = (TextView)findViewById(R.id.path); /* storing the current path*/
getDir(root);
}
private void getDir(String dirPath)
{
myPath.setText("Location: " + dirPath);
item = new ArrayList<String>();
path = new ArrayList<String>();
File f = new File(dirPath);
File[] files = f.listFiles(); /** files is an array of all the files in a directory. */
if(!dirPath.equals(root))
{
item.add(root);
path.add(root);
item.add("../");
path.add(f.getParent());
}
for(int i=0; i < files.length; i++)
{
File file = files[i];
path.add(file.getPath());
if(file.isDirectory())
item.add(file.getName() + "/");
else
item.add(file.getName());
}
ArrayAdapter<String> fileList = new ArrayAdapter<String>(this, R.layout.row, item);
setListAdapter(fileList);
}
protected void onListItemClick(ListView l, View v, int position, long id) {
File file = new File(path.get(position));
if (file.isDirectory())
{
if(file.canRead())
getDir(path.get(position));
else
{
new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle("[" + file.getName() + "] folder can't be read!")
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}).show();
}
}
else
{
new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle("[" + file.getName() + "]")
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}).show();
}
}
you can try this:
#Override
protected void onBackPressed(){
//super.onBackPressed(); //remove it if you want control
String previousDir = "build your previous dir here";
if (previousDir != null){ //if deferent root path
Intent activityDir = new Intent(this, MainActivity.class);
activityDir.putExtra("DIR_PATH", previousDir);
startActivity(activityDir);
}//end if
finish(); //close this screen to show new screen above with new path
}
Note: you have to edit onCreate(....) as bellow code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); /**super keyword in java is a reference variable that
is used to refer immediate parent class object. */
setContentView(R.layout.activity_main);
myPath = (TextView)findViewById(R.id.path); /* storing the current path*/
if(getIntent() != null){
root = getIntent().getStringExtra("DIR_PATH", root); //if is null then get root
}
getDir(root);
}

I cannot add the one arraylist into another

Actually I have one filtered array. I want to store that ArrayList in another ArrayList, but it is not adding. I am saving one model to another. because I want only that filteredlist.
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ComboViewHolder> {
private ArrayList<Products> catList;
private ArrayList<FilteredCategorymodel> filterList;
Context context;
int count = 0;
// ArrayList<FilteredCategorymodel> filterModel;
SharedPrefrences sharedPrefrences;
boolean isClicked = true;
public ProductAdapter(Context context, ArrayList<Products> catList) {
this.catList = catList;
this.context = context;
}
#Override
public ComboViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).
inflate(R.layout.combo_list_item, parent, false);
return new ComboViewHolder(itemView);
}
#Override
public void onBindViewHolder(final ComboViewHolder holder, final int position) {
final Products products = catList.get(position);
Log.e("Products Items::::", products + "");
holder.mProductName.setText(products.getProduct_name());
holder.mProductDescription.setText(products.getProduct_description());
holder.mDescription.setText(products.getRecipe_method());
holder.mPrice.setText(products.getPrice());
Picasso.with(context)
.load(Constants.Image_Path + products.getProduct_image())
.placeholder(R.drawable.common_signin_btn_icon_focus_light) // optional
.error(R.drawable.common_signin_btn_icon_dark) // optional
.into(holder.mPImage);
holder.mPImage.setTag(holder);
holder.btnIncrese.setTag(position);
holder.btnDecrese.setTag(position);
holder.btnIncrese.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int mPosition = (int) v.getTag();
Log.e("mPosition~", mPosition + "~" + position);
count = catList.get(mPosition).getCount() + 1;
for (int i = 0; i < catList.size(); i++) {
filterList = new ArrayList<FilteredCategorymodel>();
filterList.add(catList.get(i));
}
basketCount = basketCount + 1;
catList.get(mPosition).setCount(count);
holder.mQuantity.setText(Integer.toString(products.getCount()));
ProductActivity.updateSum(basketCount);
}
});
holder.btnDecrese.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// int position = (Integer) v.getTag();
int mPosition = (int) v.getTag();
if (catList.get(mPosition).getCount() < 1) {
holder.mQuantity.setText("0");
} else {
count = catList.get(mPosition).getCount() - 1;
basketCount = basketCount - 1;
catList.get(position).setCount(count);
Log.e("COUNT::::", count + "");
holder.mQuantity.setText(Integer.toString(products.getCount()));
ProductActivity.updateSum(basketCount);
// sharedPrefrences = new SharedPrefrences();
// sharedPrefrences.addFavorite(context, catList.get(mPosition));
// Toast.makeText(context, "Fave",
// Toast.LENGTH_SHORT).show();
// Log.e("COUNT::::", count + "");
}
}
});
}
#Override
public int getItemCount() {
return catList.size();
}
Because every time you create new arraylist in loop.
Do it in this way.
holder.btnIncrese.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int mPosition = (int) v.getTag();
Log.e("mPosition~", mPosition + "~" + position);
count = catList.get(mPosition).getCount() + 1;
filterList = new ArrayList<FilteredCategorymodel>();
for (int i = 0; i < catList.size(); i++) {
filterList.add(catList.get(i));
}
basketCount = basketCount + 1;
catList.get(mPosition).setCount(count);
holder.mQuantity.setText(Integer.toString(products.getCount()));
ProductActivity.updateSum(basketCount);
}
});
From this too less information, I guess You are trying to add some values to Your filterList. The problem is, that everytime Your are going through the loop, You are creating a new ArrayList:
for (int i = 0; i < catList.size(); i++) {
filterList = new ArrayList<FilteredCategorymodel>();
filterList.add(catList.get(i));
}
You have to init the filterList first, don´t do this inside the loop. Your loop must look like this:
for (int i = 0; i < catList.size(); i++) {
filterList.add(catList.get(i));
}
it´s also important what You trying to reach. If You just want to fill a new list if the button is clicked, then init Your list inside onButtonClick outside the loop. But if You want to fill that list again and again and the values should persist, then init the list inside Your constructor.
But also, in Your case, this will not work, because filterList is from type "FilteredCategoryModel" and catList is from type "Product". You cannot fill an ArrayList with a wrong type.
If you want to add one ArrayList data into another you don't need to use loop, Use addAll() of ArrayList. Please check below example.
ArrayList<YourClass> a = new ArrayList<>();
ArrayList<YourClass> b = new ArrayList<>();
b.addAll(a);
It will add all data of b into a.

ArrayIndexOutOfBoundsException / passing arraylist from alertdialog to activity

I have an alertdialog with multiple choices, I store the user's choices on an ArrayList of strings, and I want to pass the stored arraylist to the host activity (I will use the array's elements to query my database)..
When i run my app, i get an ArrayIndexOutOfBoundsException (may be the index is -1..), I'm not sure if it's the loop, or if i did not pass the arraylist correctly from the alertdialog...
can you guys take a look ? here is my function :
public void onOkay(ArrayList<String> selected) {
StringBuilder stringBuilder = new StringBuilder();
if (selected.size() != 0) {
for (int i = 0; i < selected.size(); i++) {
String categories = selected_items_array[selected.indexOf(i)];
stringBuilder = stringBuilder.append(" " + categories);
}
Toast.makeText(this, "You have selected: "
+ stringBuilder.toString(), Toast.LENGTH_SHORT).show();
}
}
logcat :
java.lang.ArrayIndexOutOfBoundsException: length=6; index=-1
at com.hichamridouane.smartshop.MainActivity.onOkay(MainActivity.java:164)
at com.hichamridouane.smartshop.TimelineSettings$2.onClick(TimelineSettings.java:71)
here is my dialogfragment class.
and here is my host activity.(as I said, i'm not sure if i'm passing correctly the arraylist to the host activity)
thanks !
It looks really strange to me, especially in
String categories = selected_items_array[selected.indexOf(i)];
From JavaDocs about indexOf
Returns the index of the first occurrence of the specified element
in this list, or -1 if this list does not contain the element.
More formally, returns the lowest index <tt>i</tt> such that
<tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
or -1 if there is no such index.
So, you try to find element in your selected_items_array (not correct name in Java)
in first iteration i == 0, selected_items_array have no such element => indexOf return -1. Array can't have element with index = -1, it starts from 0. So you have your ArrayIndexOutOfBoundsException
Problem solved. Had to use Arraylists of integers in my activity and my dialogfragment.
here is what i did in my DialogFragment class:
public class TimelineSettings extends DialogFragment {
ArrayList<Integer> selected_categories = new ArrayList<Integer>();
boolean[] itemsChecked = {false, false, false, false, false, false};
// this interface to communicate with the host activity.
public interface dialoglistener {
public void onOkay(ArrayList<Integer> selected);
public void onCancel();
}
dialoglistener mlistener;
//this function is to instantiate the dialoglistener
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mlistener = (dialoglistener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement dialogListener");
}
}
My multichoice dialog :
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
for(int i=0;i<itemsChecked.length;i++){
if(selected_categories.contains((String)String.valueOf(i)))
itemsChecked[i]=true;
}
// Set the dialog title
builder.setTitle("Choisissez vos paramètres")
.setMultiChoiceItems(R.array.categories, itemsChecked,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int indexselected,
boolean isChecked) {
if (isChecked) {
// If the user checked the item, add it to the selected items
if(!selected_categories.contains(indexselected)){
selected_categories.add(indexselected);
itemsChecked[indexselected]=true;
}
} else if (selected_categories.contains(indexselected)) {
// Else, if the item is already in the array, remove it
selected_categories.remove(indexselected);
itemsChecked[indexselected]=false;
}
}
})
// Set the action buttons
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
mlistener.onOkay(selected_categories);
}
})
.setNegativeButton("Annuler", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
mlistener.onCancel();
}
});
return builder.create();
}
On my host activity, I implemented the fragment's interface :
#Override
public void onCreate(Bundle savedInstanceState) {
/* some fancy stuff */
Resources res = getResources();
selectedArray = res.getStringArray(R.array.categories);
}
Getting the selected items (and show them on a toast, just for testing) :
#Override
public void onOkay(ArrayList<Integer> selected) {
StringBuilder stringBuilder = new StringBuilder();
if (selected.size() != 0) {
for (int i = 0; i < selected.size(); i++) {
String categories = selectedArray[selected.get(i)];
stringBuilder = stringBuilder.append(" " + categories);
}
Toast.makeText(this, "You have selected: "
+ stringBuilder.toString(), Toast.LENGTH_SHORT).show();
}
}

How to clear all items in a ListView while using List Adapter onTextChange?

I have been trying to find answers, but it has been hard to find a solution that works.
I tried setting the adapter to null, clearing the actual list but neither seems to work.
I am using a ListView with a ListAdapter and am trying to make it clear on a change of search Text when text is changed.
list.clear(); works but it does not occur on text change.
Here is my code:
private EditText search_input;
private Button search_button;
// progress bar for search results
private ProgressDialog search_loading;
private ListView wordSearchList;
private ListAdapter adapter;
// no result layout
private LinearLayout no_res;
// create list for adapter
ArrayList<HashMap<String, String>> list;
// database helper
private DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dictionary_search);
search_input = (EditText) findViewById(R.id.search_dictionary);
search_button = (Button) findViewById(R.id.search_button);
search_button.setOnClickListener(this);
// linear layout for no results
no_res = (LinearLayout) findViewById(R.id.search_result_ll);
// create hashmap list
list = new ArrayList<HashMap<String, String>>();
// remove views if they exist
search_input.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// REMOVE LIST VIEW AND ADAPTER
// list.clear();
if (no_res.getChildCount() > 0) {
no_res.removeAllViews();
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
#Override
public void onClick(View v) {
if (v == search_button) {
// clear list for fresh start
list.clear();
no_res.removeAllViews();
// validate input and that something was entered
if (search_input.getText().toString().length() < 1) {
// missing required info (null was this but lets see)
Toast.makeText(getApplicationContext(),
"Please search for something!", Toast.LENGTH_LONG)
.show();
} else {
String search_data;
search_data = search_input.getText().toString();
// remove any current views on search again
// REMOVE THE LIST VIEW
// execute the query search
List<DatabaseWordsFTS> search_results = db
.getSingleWordSearch(search_data);
// if no search results returned
if (search_results.size() <= 0) {
TextView no_results_tv = new TextView(this);
no_results_tv.setText("No results found.");
no_res.addView(no_results_tv);
}
// setup listview
wordSearchList = (ListView) findViewById(R.id.wordSearchList);
for (DatabaseWordsFTS word_found : search_results) {
// have to create hashmap in loop
HashMap<String, String> map = new HashMap<String, String>();
// convert d id to long
Integer dictionary_id_convert = (int) (long) word_found._dictionaryId;
// extract dictionary from d-id - since it is not a list and
// just a variable
DatabaseDictionary dictionary_found = db
.getDictionary(dictionary_id_convert);
// extract languages to send below
Integer dln_1 = (int) dictionary_found._language1Id;
Integer dln_2 = (int) dictionary_found._language2Id;
Integer dln_3 = (int) dictionary_found._language3Id;
Integer dln_4 = (int) dictionary_found._language4Id;
// get languages for the words based on ids passed in
List<DatabaseLanguages> LanguagesForD = db
.getAllLanguagesWithId(dln_1, dln_2, dln_3, dln_4);
// add name to hashmap and rest of the data as strings
map.put("w_1", word_found.get_word1_fts());
map.put("l_1", LanguagesForD.get(0)._language_name);
map.put("d_id", String.valueOf(dictionary_id_convert));
map.put("w_id", String.valueOf(word_found.get_id()));
if (word_found.get_word2_fts() != null) {
map.put("w_2", word_found.get_word2_fts());
map.put("l_2", LanguagesForD.get(1)._language_name);
}
if (word_found.get_word3_fts() != null) {
map.put("w_3", word_found.get_word3_fts());
map.put("l_3", LanguagesForD.get(2)._language_name);
}
if (word_found.get_word4_fts() != null) {
map.put("w_4", word_found.get_word4_fts());
map.put("l_4", LanguagesForD.get(3)._language_name);
}
list.add(map);
// used to dismiss progress bar for searching
search_loading.dismiss();
}
String[] from = { "w_1", "w_2", "w_3", "w_4" }; // , "word3",
// "word4"
int[] to = { R.id.textName, R.id.textLanguage };
adapter = new SimpleAdapter(this, list,
R.layout.dictionary_row, from, to);
wordSearchList.setAdapter(adapter);
wordSearchList
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
HashMap itemValue = (HashMap) wordSearchList
.getItemAtPosition(position);
String w_id = (String) itemValue.get("w_id");
String d_id = (String) itemValue.get("d_id");
String l_1 = (String) itemValue.get("l_1");
String l_2 = (String) itemValue.get("l_2");
String l_3 = (String) itemValue.get("l_3");
String l_4 = (String) itemValue.get("l_4");
String w_1 = (String) itemValue.get("w_1");
String w_2 = (String) itemValue.get("w_2");
String w_3 = (String) itemValue.get("w_3");
String w_4 = (String) itemValue.get("w_4");
// Show Alert
Toast.makeText(
getApplicationContext(),
"Position :" + itemPosition
+ " ListItem : " + w_id,
Toast.LENGTH_LONG).show();
// creating bundle
Bundle d_data = new Bundle();
// add to bundle
d_data.putString("w_id", w_id);
d_data.putString("wd_id", d_id);
d_data.putString("w_1", w_1);
d_data.putString("l_1", l_1);
// get tags only if it exists
if (w_2 != null) {
d_data.putString("w_2", w_2);
d_data.putString("l_2", l_2);
}
if (w_3 != null) {
d_data.putString("w_3", w_3);
d_data.putString("l_3", l_3);
}
if (w_4 != null) {
d_data.putString("w_4", w_4);
d_data.putString("l_4", l_4);
}
// start new intent based on the tag -
Intent single_word_view = new Intent(
DictionaryWordSearch.this,
DictionarySingleWordView.class);
// call extras
single_word_view.putExtras(d_data);
// new_dictionary_view.putExtra("d_id",
// WhatAmISupposeToPassInHere);
startActivity(single_word_view);
}
});
}
EDIT: (Below worked for me)
Changed ListAdapter to SimpleAdapter
if(adapter != null){list.clear(); adapter.notifyDataSetChanged();}
Added the above code in onTextChange
Look if you want the TextView with no result you can implement this code
listView.setEmptyView(emptyView)
and pass your TextView to this method ,
for clearing the ListView you can clear your collection and call notifyChangeDataSet or set adapter with null try both and feed me back

Categories

Resources