Android java : How to auto refresh list view - java

I currently develop a File Explorer app and I need to have a auto refresh for my listview.
Because when I delete the item I still can see the item , I need to back the folder and go inside the folder again only see it disappear. How to auto refresh so when I deleted the item it disappear itself.
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
FileInfo fileDescriptor = fileArrayListAdapter.getItem(position);
if (fileDescriptor.isFolder() || fileDescriptor.isParent()) {
currentFolder = new File(fileDescriptor.getPath());
fill(currentFolder);
//
} else {
fileSelected = new File(fileDescriptor.getPath());
Intent intent = new Intent();
intent.putExtra(Constants.KEY_FILE_SELECTED,
fileSelected.getAbsolutePath());
setResult(Activity.RESULT_OK, intent);
Log.i("FILE CHOOSER", "result ok");
MimeTypeMap map = MimeTypeMap.getSingleton();
String ext = MimeTypeMap.getFileExtensionFromUrl(fileSelected.getName());
String type = map.getMimeTypeFromExtension(ext);
if (type == null){
type = "*/.jpeg*";
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(fileSelected), "image/*");
// intent.setDataAndType(data, type);
}else {
type = "*/.txt*";
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(fileSelected), "text/*");
// intent.setDataAndType(data, type);
}
//finish();
// intent.setAction(android.content.Intent.ACTION_VIEW);
startActivity(intent);
// Intent intent = new Intent();
this.getListView().setLongClickable(true);
this.getListView().setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id) {
new AlertDialog.Builder(ViewNoteActivity.this) .setTitle("Delete File")
.setMessage("Do You Want To Delete this file ?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int button){
fileSelected.delete();
Toast.makeText(getBaseContext(), "File has been deleted." , Toast.LENGTH_SHORT ).show();
adapter.notifyDataSetChanged();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int button){
}
}).show();
return true;
}
});
}
}
public static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i=0; i<children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
return dir.delete();
}

Delete item from the datasource that populates listview and call notifyDataSetChanged on the adapter to refresh listView

You need to delete ListItem from ArrayList from Adapter and call notifyDatasetChanged() ,
When you call notifyDatasetChanged() method it will refresh your listview with ArrayList with updated data so, you have to first delete item from ArrayList onClick of Delete Button.
And then you have to call notifyDatasetChanged().

Related

deleting item in sharedPreferences from recyclerView adapter

i tried to delete an item in sharedPreferences, in recyclerView adapter. but that item doesn't disappear till I go back from the activity and come back. I need it to disappear soon after being deleted.
Method
public boolean RemoveFromWantToRead(AllBooksActivityModel book) {
ArrayList<AllBooksActivityModel>books = getWantToReadBooks();
if (null != books){
for (AllBooksActivityModel b: books){
if (b.getBookID() == book.getBookID()){
if (books.remove(b)){
//We create a 'if' loop here is if only the thing happened, the loop actions.
Gson gson = new Gson();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove(WANT_TO_READ_BOOKS);
editor.putString(WANT_TO_READ_BOOKS,gson.toJson(books));
editor.commit();
return true;
}
} }
}return false;
}
This is how I tried to delete an item.
holder.BtnDltTxt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("Do you want to delete this massage");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String EleName = allBooksActivityModels.get(position).getBookName();
if( Ulitls.getInstance(context).RemoveFromCurrenlyReading(allBooksActivityModels.get(position))){
Toast.makeText(context, EleName + " Removed", Toast.LENGTH_SHORT).show();
notifyDataSetChanged();
}else{
Toast.makeText(context, "Something Wrong Happens, Try again", Toast.LENGTH_SHORT).show();
}
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.create().show();
}
});

Android DialogFramgment loads item from arrayList twice but only on Samsung

I am cleaning up some code where a DialogFrament i supposed to diaplay items from an ArrayList (ref. "arr" in the code) and then the user can choose severeal items from it and then hit OK. This work fine, no problemo. But, only on Samsung Phones, the DialogFrament lists the item from the ArrayList twice. so, on all the other phone the list displays the values arr[0]->arr[n] but on Samsung(again ONLY on Samsung) the values are arr[0]->arr[n] + arr[0]->arr[n]. Since it's the same code for all android phones but the problem only occurs on Samsung Phones, im out of ideas.
A quick google search pointed me towards a difference in layout rules by Samsung depending on the resolution of their phone but it seeamed unlikely.
Have any of you heard about this before?
CODE FOR MY FRAGMENT
public ArrayList mSelectedItems;
public int type;
public boolean single = false;
int count;
boolean search;
public int single_item = -1;
public interface CategoriesDialogFragmentListener {
public void onOkay(ArrayList items, int type);
public void onCancel();
public void onSingleOkay(int item, int type);
}
CategoriesDialogFragmentListener mListener;
public void setType(int type_id) {
/*
1 = Category
2 = Genre
3 = Availability
*/
type = type_id;
}
public void setSearch(boolean isSearch) {
search = isSearch;
}
public void setList(ArrayList temp) {
mSelectedItems = temp;
}
public void isSingle(boolean is_single){
single = is_single;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Verify that the host activity implements the callback interface
try {
// Instantiate the NoticeDialogListener so we can send events to the host
mListener = (CategoriesDialogFragmentListener) activity;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(activity.toString()
+ " must implement NoticeDialogListener");
}
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
mSelectedItems = new ArrayList(); // Where we track the selected items
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Set the dialog title
CharSequence[] arr;
String title;
switch(type){
case 1:
title = "Välj kategori";
arr = MainActivity.CATEGORY_STRINGS.toArray(new CharSequence[MainActivity.CATEGORY_STRINGS.size()]);
single = true;
break;
case 2:
title = "Välj genre";
arr = MainActivity.GENRE_STRINGS.toArray(new CharSequence[MainActivity.GENRE_STRINGS.size()]);
single = false;
break;
case 3:
title = "Välj tillgängligheter";
arr = MainActivity.AVAIL_STRINGS.toArray(new CharSequence[MainActivity.AVAIL_STRINGS.size()]);
single = false;
break;
default:
title = "ett fel uppstod";
arr = MainActivity.CATEGORY_STRINGS.toArray(new CharSequence[MainActivity.CATEGORY_STRINGS.size()]);
}
if(!single) {
if(type == 2 && search == false) {
count = 0;
builder.setTitle(title).setMultiChoiceItems(arr, null,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
//Kod för att starta fragment med valda entiteter
/*
if(mSelectedItems != null || !mSelectedItems.isEmpty()){
for(Object e : mSelectedItems){
}
}
*/
if (isChecked) {
if (count < 5) {
mSelectedItems.add(which);
count++;
} else {
new android.app.AlertDialog.Builder(getActivity())
.setTitle(R.string.five)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
((AlertDialog) dialog).getListView().setItemChecked(which, false);
}
} else if (mSelectedItems.contains(which)) {
// Else, if the item is already in the array, remove it
mSelectedItems.remove(Integer.valueOf(which));
count--;
}
}
})
// Set the action buttons
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// User clicked OK, so save the mSelectedItems results somewhere
// or return them to the component that opened the dialog
mListener.onOkay(mSelectedItems, type);
}
})
.setNegativeButton("Avbryt", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
CategoriesDialogFragment.this.getDialog().cancel();
}
});
}else{
builder.setTitle(title).setMultiChoiceItems(arr, null,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
if (isChecked) {
mSelectedItems.add(which);
} else if (mSelectedItems.contains(which)) {
// Else, if the item is already in the array, remove it
mSelectedItems.remove(Integer.valueOf(which));
}
}
})
// Set the action buttons
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// User clicked OK, so save the mSelectedItems results somewhere
// or return them to the component that opened the dialog
mListener.onOkay(mSelectedItems, type);
}
})
.setNegativeButton("Avbryt", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
CategoriesDialogFragment.this.getDialog().cancel();
}
});
}
} else {
builder.setTitle(title).setSingleChoiceItems(arr, -1, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
single_item = item;
}
})
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// User clicked OK, so save the mSelectedItems results somewhere
// or return them to the component that opened the dialog
mListener.onSingleOkay(single_item, type);
}
})
.setNegativeButton("Avbryt", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
CategoriesDialogFragment.this.getDialog().cancel();
}
});;
}
return builder.create();
}
}

Listview not refreshing deleted row from data base

I have a database of addresses. I just want the user to be able to delete a row but the list wont update. I have seen all the other people's examples but they are not working for me. I keep trying variations of different things. They all produce no effect. I have to change activities and then it deletes.
I add the address in one activity and end it with a finish();
public void onItemClick(AdapterView <?> adapterView, View view, int position, long id) {
String str = (String) adapterView.getItemAtPosition(position);
Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
db = new DatabaseHandler(this);
db.addAddress(str);
Intent intent= new Intent();
setResult(RESULT_OK, intent);
finish();
}
Here is my deleteAddress() for mylistview and i use it in on resume.
private void deleteAddress(){
listview= (ListView)findViewById(R.id.listView);
listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> a, View v, int position, long id) {
final String selectedID = String.valueOf(position);
AlertDialog.Builder adb=new AlertDialog.Builder(Address.this);
adb.setTitle("Delete?");
adb.setMessage("Are you sure you want to delete?");
final int positionToRemove = position;
adb.setNegativeButton("Cancel", null);
adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dbHelper.deleteAddress(selectedID);
updateList();
}});
adb.show();
return true;
}
});
}
public void updateList(){
dbHelper.fetchAllAddresses();
dataAdapter.notifyDataSetChanged();
Here is my deleteAddress in database
public void deleteAddress(String rowId) {
// 1. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// 2. delete
db.delete(TABLE_CONTACTS, //table name
"_id"+"=?", // selections
new String[] {rowId}); //selections args
// 3. close
db.close();
}
here is my listview
public void onResume() {
super.onResume();
deleteAddress();
cursor= dbHelper.fetchAllAddresses();
String columns[]= new String[]{
dbHelper.KEY_NAME
};
int[] to = new int[] {
R.id.rowTextView,
};
dataAdapter= new SimpleCursorAdapter(
this,R.layout.simplerow, cursor,columns,to,0);
dataAdapter.notifyDataSetChanged();
listview= (ListView)findViewById(R.id.listView);
listview.setAdapter(dataAdapter);
}
you are using position as row id, in your deleteAddress method, but you should id, parameter of onItemClick instead. Change
final String selectedID = String.valueOf(position);
with
final String selectedID = String.valueOf(id);
How looks your adapter? You need to delete the item in the adapters-item-list, not just in the database... Do that and then call notifyDataSetChanged()!
I am not correcting your code as there is a lot can fix, just providing your answer in your way, try this
public void updateList(){
cursor= dbHelper.fetchAllAddresses();
String columns[]= new String[]{
dbHelper.KEY_NAME
};
int[] to = new int[] {
R.id.rowTextView,
};
dataAdapter= new SimpleCursorAdapter(
this,R.layout.simplerow, cursor,columns,to,0);
listview.setAdapter(dataAdapter);
}

Android java : delete selected file / folder

How to delete the selected file / folder by using long pressed ?
I'm developing an File Explorer app and there are listed folder and file from my storage.
I want to have a delete function for the longpressed().
public void longpressed(){
this.getListView().setLongClickable(true);
this.getListView().setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id) {
new AlertDialog.Builder(ViewNoteActivity.this , AlertDialog.THEME_HOLO_DARK)
.setTitle("Delete Folder / File")
.setMessage("Are you sure you want to delete the selected folder / file ?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which ) {
boolean success = true;
if (success) {
Toast.makeText(getBaseContext(), "You have successfully delete." , Toast.LENGTH_SHORT ).show();
} else {
Toast.makeText(getBaseContext(), "You have Failed to delete." , Toast.LENGTH_SHORT ).show();
}
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.setIcon(R.drawable.ic_launcher)
.show();
return true;
}
});
}
item select coding:
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
FileInfo fileDescriptor = fileArrayListAdapter.getItem(position);
if (fileDescriptor.isFolder() || fileDescriptor.isParent()) {
currentFolder = new File(fileDescriptor.getPath());
fill(currentFolder);
} else {
fileSelected = new File(fileDescriptor.getPath());
Intent intent = new Intent();
intent.putExtra(Constants.KEY_FILE_SELECTED,
fileSelected.getAbsolutePath());
setResult(Activity.RESULT_OK, intent);
Log.i("FILE CHOOSER", "result ok");
}
}
See the File class API reference.
To delete a file:
new File(path).delete()
To delete a folder:
private void deleteFolderRecursive(File dir) {
File[] files = dir.listFiles();
if (files != null) {
for (File file : files) {
if (file.isDirectory()) {
deleteFolderRecursive(file);
} else {
file.delete();
}
}
}
dir.delete();
}
Do this:
File dir =new File(getActivity().getApplicationContext().getFilesDir()+"/YourFOlderName");
boolean success = deleteDir(dir);
Where:
getActivity().getApplicationContext().getFilesDir()+"/YourFOlderName"
is the path to the folder.
And:
public static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i=0; i<children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
return dir.delete();
}
The above will delete all the children inside the directory.
if your folder is on the External SD Card the path should be mounted like:
Never hardcode the sdcard, you must use
Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
will let you know if the memory is loaded. Then use:
Environment.getExternalStorageDirectory().getAbsolutePath()

Duplicate screen shot of first fragment

I have 2 fragments. First one is a checklist for live electrical work(safety check list)
, and a second fragmet which is also a checklist (non- live electrical work).
What I'm doing is getting the user to take a screen shot of each fragment when they click "next". This is achieved by getting the user to click the "next" button which will take a screen shot of the current fragment, then loading the next fragment(goes from liveWorkFragment -> nonLiveWorkFragment). Same thing on the second fragment. The problem I am having is that the first fragment takes a screen shot no problem, it gets saved in the correct folder etc, but when I click next on the second fragment, it takes the screenshot, but when I go to look at the picture(fragment2 screenshot is called "SafetyCheckList2.png"), it's the same picture as fragment1. I have no idea why.
This is the code to take a screen shot for fragment1:
View.OnClickListener clickListener = new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(v.getId() == R.id.btnNext)
{
try
{
View u = view.findViewById(R.id.liveWorkLayout).getRootView();
u.setDrawingCacheEnabled(true);
Bitmap b = u.getDrawingCache();
//Setup the directory
File mediaFolder = new File(context.getExternalFilesDir(null)+"/ArcFlash/CheckListMedia");
if(!mediaFolder.exists())
mediaFolder.mkdirs();
File fileName = new File(context.getExternalFilesDir(null)+"/ArcFlash/SafetyCheckList1.png");//CheckListMedia
FileOutputStream out = new FileOutputStream(fileName);
b.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
Toast.makeText(context, "Saved Picture", Toast.LENGTH_SHORT).show();
new AlertDialog.Builder(context)
.setTitle("Continue")
.setMessage("You cannot return to this page after clicking next.")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
FragmentManager fm = getFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
Fragment newFragment = new NonLiveWorkFragment();
transaction.replace(R.id.mainLayout, newFragment);
//transaction.addToBackStack("first");
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
transaction.commit();
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.show();
}
catch(Exception ex)
{
handler.Log(ex.getMessage(), "onClick (LiveWorkFragment.java)", context);
}
}
}
};
Code for fragment2:
View.OnClickListener clickListener = new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(v.getId() == R.id.frag2Next)
{
try
{
View u = view.findViewById(R.id.nonLiveWorkLayout).getRootView();
u.setDrawingCacheEnabled(true);
Bitmap b = u.getDrawingCache();
File fileName = new File(context.getExternalFilesDir(null)+"/ArcFlash/SafetyCheckList2.png");
FileOutputStream out = new FileOutputStream(fileName);
b.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
Toast.makeText(context, "Saved Picture", Toast.LENGTH_LONG).show();
//Until I figure out how the heck to draw with a silly(being PG 13 here..) fragment,
//I'm going to use an activity as the final page
new AlertDialog.Builder(context)
.setTitle("Continue")
.setMessage("You cannot return to this page after clicking next.")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent signatures = new Intent();
signatures.setClass(getActivity(), Signature.class);
startActivity(signatures);
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.show();
}
catch(Exception ex)
{
handler.Log(ex.getMessage(), "onClick Next (NonLiveWorkFragment.java)", context);
Toast.makeText(context, "Couldn't load next page.", Toast.LENGTH_LONG).show();
}
}
}
};

Categories

Resources