How to share the multiple files? [duplicate] - java

This question already has answers here:
how to attach multiple files to email client in android
(5 answers)
Closed 3 years ago.
I have done coding for selected multiple listview items to be shared but the problem is when i select the multiple items it shares only one item, the remaining items are not selected.Please help me how to share the multiple listview items .
public class MainActivity extends AppCompatActivity {
TextView textView;
ListView listView;
List<String> myList;
String MEDIA_PATHS;
Uri uri;
int count = 0;
ArrayList<String> arrayList2 = new ArrayList<>();
String MEDIA_PATH = new String(Environment.getExternalStorageDirectory() + "/CallLogs" );
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(R.id.list_items);
textView = (TextView)findViewById(R.id.textView);
myList = new ArrayList<String>();
final File files = new File(MEDIA_PATH);
File list[] = files.listFiles();
for (int i = 0; i < list.length; i++) {
myList.add(list[i].getName());
}
final ArrayAdapter adapter = new ArrayAdapter(this,R.layout.list_layout,R.id.textView,myList);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
listView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
#Override
public void onItemCheckedStateChanged(ActionMode actionMode, int position, long l, boolean b) {
count = count+1;
actionMode.setTitle(count + " items selected");
MEDIA_PATHS = new String(Environment.getExternalStorageDirectory() + "/CallLogs/" + myList.get(position));
// arrayList2.add(myList.get(position));
arrayList2.add(MEDIA_PATH);
}
#Override
public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
MenuInflater inflater = actionMode.getMenuInflater();
inflater.inflate(R.menu.list_menu,menu);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
switch (menuItem.getItemId())
{
case R.id.delete_id:
for(String msg : arrayList2) {
adapter.remove(msg);
}
Toast.makeText(getApplicationContext(),"deleted",Toast.LENGTH_SHORT).show();
count=0;
actionMode.finish();
return true;
// break;
case R.id.share_id:
for(String msg : arrayList2) {
uri = Uri.parse(msg);
}
// Uri uri = Uri.parse(MEDIA_PATHS);
Intent share = new Intent(Intent.ACTION_SEND);
share.putExtra(Intent.EXTRA_STREAM, uri);
share.setType("audio/*");
share.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(share, "Share audio File"));
return true;
default:
Toast.makeText(getApplicationContext(),"Nothing selected",Toast.LENGTH_SHORT).show();
break;
}
return false;
}
#Override
public void onDestroyActionMode(ActionMode actionMode) {
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
// myList.get(position);
adapterView.setSelected(true);
}
});
}
}

Please refer this link for more information about sharing the files.I tried it,works for me.
https://developer.android.com/training/sharing/send.html

Related

notifyDataSetChanged(); not refreshing ListView?

I'm working on a notes app and I'm running into trouble deleting notes: after the note is deleted, it still shows in the listview.
I'm trying to use notifyDataSetChanged(), but it doesn't seem to be working for me.
MainActivity:
public class MainActivity extends AppCompatActivity {
private ListView mListViewNotes;
ArrayAdapter<Note> listAdapter;
ArrayList<Note> list_items = new ArrayList<>();
int count = 0;
String list_item;
Object mActionMode;
Toolbar app_bar;
ArrayList<Note> notes;
private String mNoteFileName;
private Note mLoadedNote;
Note loadedNote;
ImageView picTest;
NoteAdapter na;
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
app_bar = (Toolbar) findViewById(R.id.app_bar);
TextView title_1 = (TextView) findViewById(R.id.title1);
TextView title_2 = (TextView) findViewById(R.id.title2);
TextView title_m = (TextView) findViewById(R.id.title_m);
Typeface music_font = Typeface.createFromAsset(getAssets(), "fonts/melodymakernotesonly.ttf");
Typeface notes_font = Typeface.createFromAsset(getAssets(), "fonts/the unseen.ttf");
setSupportActionBar(app_bar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setElevation(12);
title_1.setTypeface(music_font);
title_2.setTypeface(notes_font);
title_m.setTypeface(music_font);
listAdapter = new ArrayAdapter<Note>(this, R.layout.item_note, R.id.item_note, list_items);
mNoteFileName = getIntent().getStringExtra("NOTE_FILE");
if (mNoteFileName != null && !mNoteFileName.isEmpty()) {
loadedNote = Utilities.getNoteByName(this, mNoteFileName);
}
mListViewNotes = (ListView) findViewById(R.id.listview_notes);
mListViewNotes.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
mListViewNotes.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
if (list_items.contains(notes.get(position))) {
count = count-1;
list_items.remove(notes.get(position));
mode.setTitle(count + " Notes Selected");
} else {
count = count+1;
list_items.add(notes.get(position));
mode.setTitle(count + " Notes Selected");
}
if (count == 0) {
mode.setTitle("No Notes Selected");
}
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
app_bar.setVisibility(View.GONE);
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
deleteNote();
return true;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
count = 0;
app_bar.setVisibility(View.VISIBLE);
list_items.clear();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.add_note:
startActivity(new Intent(this, NoteActivity.class));
break;
case R.id.action_settings:
Log.d("list:", "testing");
}
return true;
}
#Override
protected void onResume() {
super.onResume();
mListViewNotes.setAdapter(null);
notes = Utilities.getAllSavedNotes(this);
if (notes == null || notes.size() == 0) {
Toast.makeText(this, "No Notes!", Toast.LENGTH_LONG).show();
} else {
na = new NoteAdapter(this, R.layout.item_note, notes);
mListViewNotes.setAdapter(na);
mListViewNotes.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String filename = ((Note) mListViewNotes.getItemAtPosition(position)).getDateTime() + Utilities.FileExtention;
Intent view_note = new Intent(getApplicationContext(), NoteActivity.class);
view_note.putExtra("NOTE_FILE", filename);
startActivity(view_note);
}
});
}
}
private void deleteNote() {
if(list_items.contains(null)) {
finish();
} else {
AlertDialog.Builder dialog = new AlertDialog.Builder(this)
.setTitle("Delete")
.setMessage("Are you sure?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
for (Note loadedNote : list_items) {
Utilities.deleteNote(getApplicationContext(), loadedNote.getDateTime() + Utilities.FileExtention);
}
na.notifyDataSetChanged();
listAdapter.notifyDataSetChanged();
}
})
.setNegativeButton("No", null)
.setCancelable(false);
dialog.show();
}
}
NoteAdapter
public class NoteAdapter extends ArrayAdapter<Note> {
public NoteAdapter(Context context, int resource, ArrayList<Note> notes) {
super(context, resource, notes);
}
#Override
public View getView(int position, View convertView, #NonNull ViewGroup parent) {
//return super.getView(position, convertView, parent);
if(convertView == null) {
convertView = LayoutInflater.from(getContext())
.inflate(R.layout.item_note, null);
}
Note note = getItem(position);
if(note != null) {
TextView title = (TextView) convertView.findViewById(R.id.list_note_title);
TextView content = (TextView) convertView.findViewById(R.id.list_note_content);
TextView date = (TextView) convertView.findViewById(R.id.list_note_date);
Typeface scribble_card = Typeface.createFromAsset(getContext().getAssets(), "fonts/the unseen.ttf");
title.setTypeface(scribble_card);
content.setTypeface(scribble_card);
title.setText(note.getTitle());
date.setText(note.getDateTimeFormatted(getContext()));
if(note.getContent().length() > 25) {
content.setText(note.getContent().substring(0,25) + "...");
} else {
content.setText(note.getContent());
}
if(note.getContent().length() <= 0) {
content.setText("(Empty Note..)");
} else {
content.setText(note.getContent());
}
if (note.getTitle().length() <= 0) {
title.setText("(Untitled)");
} else {
title.setText(note.getTitle());
}
}
return convertView;
}
You are setting adapter with a list:
na = new NoteAdapter(this, R.layout.item_note, notes);
mListViewNotes.setAdapter(na);
na.notifyDataSetChanged(); will only work if your notes list is changed.
And I don't see that you remove/add/modify on notes list.
If you are deleting item from list you need to remove it from notes list, too:
notes.remove(position_to_remove);
na.notifyDataSetChanged();

Delete multiple rows in a ListVIew

I've got a Lsitview populated with CheckedTextViews. My goal is to be able to delete multiple rows at onece, if possible with MultiChoiceModeListener.
To use it, I have to set the ListView CHOICE_MODE_MULTIPLE_MODAL.
The frist problem is now: I cant just chek the checkboxes now, because the listview isnt ChOICE_MODE_MULTIPLE anymore.
I hade the idear to set it CHOICE MODE MULTIPLE and just set an OnItemClickListenerfor the ListView, but then the ChoiceModeMultiple and its Method onItemStateChaed Method always gets called, even if i just wanna check a checkbox in my App.
Any solutions on how to fix that?
The Code (layout is the ListVIew) :
layout.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
#Override
public void onItemCheckedStateChanged(android.view.ActionMode actionMode, int i, long l, boolean b) {
if (!list_items.contains(list.get(i))) {
count++;
list_items.add(list.get(i));
actionMode.setTitle(count + " items selected");
} else if (list_items.contains(list.get(i))) {
count--;
list_items.remove(list.get(i));
actionMode.setTitle(count + " items selected");
}
}
}
Try this example, please refer this and solve
public class MainActivity extends AppCompatActivity {
ListView list;
ArrayAdapter<String> arrayAdapter;
ArrayList<String> arrayList = new ArrayList<>();
ArrayList<String> arrayList2 = new ArrayList<>();
int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView)findViewById(R.id.listItems);
arrayList.add("one");
arrayList.add("two");
arrayList.add("three");
arrayList.add("four");
arrayList.add("five");
arrayAdapter = new ArrayAdapter<String>(this,R.layout.list_layout,R.id.textView,arrayList);
list.setAdapter(arrayAdapter);
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
list.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
#Override
public void onItemCheckedStateChanged(ActionMode actionMode, int position, long l, boolean b) {
count = count+1;
actionMode.setTitle(count + " items selected");
arrayList2.add(arrayList.get(position));
}
#Override
public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
MenuInflater inflater = actionMode.getMenuInflater();
inflater.inflate(R.menu.list_menu,menu);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
switch (menuItem.getItemId())
{
case R.id.delete_id:
for(String msg : arrayList2) {
arrayAdapter.remove(msg);
}
Toast.makeText(getApplicationContext(),"deleted",Toast.LENGTH_SHORT).show();
count=0;
actionMode.finish();
return true;
default:
Toast.makeText(getApplicationContext(),"Nothing selected",Toast.LENGTH_SHORT).show();
break;
}
return false;
}
#Override
public void onDestroyActionMode(ActionMode actionMode) {
}
});
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
adapterView.setSelected(true);
}
});
}
}

Storing data and passing to next activity pausing and resuming activity

I am trying to make a basic shopping cart android application
Here is how the code looks
Items.java
public class Items extends AppCompatActivity {
private ListView lvUsers;
private ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub);
Intent intent = getIntent();
int subCategoryId = intent.getIntExtra("parameter_name", 1);
dialog = new ProgressDialog(this);
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.setMessage("Loading, please wait.....");
lvUsers = (ListView) findViewById(R.id.lvUsers);
String url = "http://146.185.178.83/resttest/subCategories/" + subCategoryId +"/items/";
new JSONTask().execute(url);
}
public class JSONTask extends AsyncTask<String, String, List<ItemModel> > {
#Override
protected void onPreExecute(){
super.onPreExecute();
dialog.show();
}
#Override
protected List<ItemModel> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line ="";
while ((line=reader.readLine()) !=null){
buffer.append(line);
}
String finalJson = buffer.toString();
JSONArray parentArray = new JSONArray(finalJson);
List<ItemModel> itemModelList = new ArrayList<>();
Gson gson = new Gson();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
ItemModel itemModel = gson.fromJson(finalObject.toString(), ItemModel.class);
itemModelList.add(itemModel);
}
return itemModelList;
}catch (MalformedURLException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if(connection !=null) {
connection.disconnect();
}
try {
if (reader !=null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<ItemModel> result) {
super.onPostExecute(result);
dialog.dismiss();
ItemAdapter adapter = new ItemAdapter(getApplicationContext(), R.layout.row_item, result);
lvUsers.setAdapter(adapter);
}
}
public class ItemAdapter extends ArrayAdapter {
public List<ItemModel> itemModelList;
private int resource;
private LayoutInflater inflater;
public ItemAdapter(Context context, int resource, List<ItemModel> objects) {
super(context, resource, objects);
itemModelList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if(convertView == null){
holder = new ViewHolder();
convertView=inflater.inflate(resource, null);
holder.tvItemName = (TextView) convertView.findViewById(R.id.tvItemName);
holder.tvPrice = (TextView) convertView.findViewById(R.id.tvPrice);
convertView.setTag(holder);
}else {
holder = (ViewHolder) convertView.getTag();
}
holder.tvItemName.setText(itemModelList.get(position).getItemName());
holder.tvPrice.setText("Rs " + itemModelList.get(position).getSalesRate());
final String itemName = itemModelList.get(position).getItemName();
final String salesRate = itemModelList.get(position).getSalesRate();
Intent intent = new Intent(Items.this, CartDisplay.class);
intent.putExtra("itemName", itemName);
intent.putExtra("salesRate", salesRate);
return convertView;
}
class ViewHolder{
private TextView tvItemName;
private TextView tvPrice;
}
}
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem add_item = menu.findItem(R.id.action_add_item);
add_item.setVisible(false);
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.testmenu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.action_show_cart:
cartMenuItem();
break;
}
return true;
}
private void cartMenuItem() {
Intent intent = new Intent(Items.this, CartDisplay.class);
startActivity(intent);
finish();
}
}
CartDisplay.java
public class CartDisplay extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.row_cart_display);
TextView tvItemName = (TextView) findViewById(R.id.tvItemName);
TextView tvSalesRate = (TextView) findViewById(R.id.tvSalesRate);
TextView tvTotalAmount = (TextView) findViewById(R.id.tvTotalAmount);
Intent intent = getIntent();
String itemName = intent.getStringExtra("itemName");
tvItemName.setText(itemName);
String salesRate = intent.getStringExtra("salesRate");
tvSalesRate.setText("RS"+salesRate);
tvTotalAmount.setText("Total: RS"+salesRate);
}
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem show_cart = menu.findItem(R.id.action_show_cart);
show_cart.setVisible(false);
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.testmenu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.action_add_item:
addMenuItem();
break;
}
return true;
}
private void addMenuItem() {
Intent intent = new Intent(this, Categories.class);
startActivity(intent);
finish();
}
}
Here is how the item layout looks
Here is how the CartDisplay layout looks
The issue at the moment is I am not able to send data to CartDisplay
Activity also I need help with implementing few other things
In Items Activity, how do I make EditText between - and + button to
show the number based on the clicks on + and - button it should not
go below zero (ie like no negative figures its like x1 or x2 or x3
etc)
When pressed on itemAddToCart button (its the cart button inside the
item list ) , it must add item to cart and not move to CartDisplay
activity , it must also send the no of items added (because its
needed there ie in CartDisplay layout needs to show this in EditText
there).
When there is an update in Cart (i.e like once we have Added an item
to cart) need to show update on cart icon on Action bar with little
+1 or where there is two items in cart +2 or anything similar , the cart icon is an menu_item if pressed here it will take you to
CartDisplay activity how to code this ?
Also how to code it to send info of multiple selected items to cart?
when pressed on cart icon it must show the updates and the last
activity must be paused ? now i have menu item in CartDisplay
Activity which will take me back to Items Activity , so i can add
more items to the cart , the process continues until i checkout or
Clear cart .
Also I need help to write code for Clear cart .
My project is open source at github there you can see my full code

onclicklistener on seperatedlistadapter

How can i implement a onclicklistener so if one item is clicked i get the object. i want something like this-
//#Override
//public void onListItemClick(ListView l, View v, int position, long id) {
//Contact c = getItem(position);
//Intent i = new Intent(getActivity(),ContactPagerActivity.class);
//i.putExtra(ShowContactFragment.EXTRA_CONTACT_ID, c.getmId());
//startActivity(i);
//}
Contact is a class for a obejct that have attributes like name, id, address
Here is my code--
public class ContactListFragment extends ListFragment {
private ArrayList<Contact> mContacts;
private static final String TAG = "CrimeListFragment";
SeparatedListAdapter adapter2;
ListView list;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
getActivity().setTitle(R.string.contact_title);
mContacts = ContactLab.get(getActivity()).getContacts();
adapter2 = new SeparatedListAdapter(getActivity());
organizeList();
}
#Override
public void onResume(){
super.onResume();
mContacts = ContactLab.get(getActivity()).getContacts();
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.contact_contact_list, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.menu_item_new_contact:
Contact contact = new Contact();
ContactLab.get(getActivity()).addContact(contact);
Intent i = new Intent(getActivity(), ContactActivity.class);
i.putExtra(ContactFragment.EXTRA_CONTACT_ID_CF, contact.getmId());
startActivityForResult(i, 0);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void organizeList(){
ArrayList<ArrayList> arrayLists = new ArrayList<ArrayList>();
char firstChar;
int firstIndex=0;
int secondIndex=1;
for(int i=firstIndex; i<mContacts.size();){
ArrayList<String> names = new ArrayList<String>();
names.add(mContacts.get(i).getmName());
if(i == mContacts.size()-1){
arrayLists.add(names);
firstIndex++;
}
firstChar = mContacts.get(i).getmName().charAt(0);
innerloup:
for(int ii=secondIndex; ii<mContacts.size();){
if(firstChar == mContacts.get(ii).getmName().charAt(0)){
names.add(mContacts.get(ii).getmName());
secondIndex++;
if(secondIndex == mContacts.size())
{
firstIndex = secondIndex;
arrayLists.add(names);
}
}
else{
arrayLists.add(names);
firstIndex = secondIndex;
secondIndex++;
ii=secondIndex;
break innerloup;
}
ii=secondIndex;
}
i = firstIndex;
}
for(int i =0; i<arrayLists.size(); i++)
{
ArrayList<String> array = arrayLists.get(i);
String name = array.get(0);
char charFirst = name.charAt(0);
adapter2.addSection(Character.toString(charFirst), new ArrayAdapter<String>(getActivity(),
R.layout.list_item, arrayLists.get(i)));
}
setListAdapter(adapter2);
}
}
The correct answer is
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Contact c = (Contact) adapter2.getItem(position);
Intent i = new Intent(getActivity(),ContactPagerActivity.class);
i.putExtra(ShowContactFragment.EXTRA_CONTACT_ID, c.getmId());
startActivity(i);
//}

Prevent activity to reload when acessing contextual action menu by clicking on a image in async gridview

I have a bunch of images from sdcard that are load asynchronously on a gridview. Everything works fine, but when accessing a multi select contextual action menu by long clicking in any image the entire activity reloads and all images are loaded again. How to prevent it?
Myadapter
public class PhotosGridViewImageAdapter extends BaseAdapter {
AsyncTaskLoadFiles myAsyncTaskLoadFiles;
public class AsyncTaskLoadFiles extends AsyncTask<Void, String, Void> {
File targetDirector;
PhotosGridViewImageAdapter myTaskAdapter;
public AsyncTaskLoadFiles(PhotosGridViewImageAdapter adapter) {
myTaskAdapter = adapter;
}
#Override
protected void onPreExecute() {
String ExternalStorageDirectoryPath = Environment
.getExternalStorageDirectory().getAbsolutePath();
String targetPath = ExternalStorageDirectoryPath + File.separator + AppConstant.PHOTO_ALBUM + File.separator;
targetDirector = new File(targetPath);
myTaskAdapter.clear();
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
File[] files = targetDirector.listFiles();
Arrays.sort(files);
for (File file : files) {
publishProgress(file.getAbsolutePath());
if (isCancelled()) break;
}
return null;
}
#Override
protected void onProgressUpdate(String... values) {
myTaskAdapter.add(values[0]);
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Void result) {
myTaskAdapter.notifyDataSetChanged();
super.onPostExecute(result);
}
}
ArrayList<String> itemList = new ArrayList<String>();
void add(String path) {
itemList.add(path);
}
void clear() {
itemList.clear();
}
void remove(int index){
itemList.remove(index);
}
private Activity _activity;
private ArrayList<String> _filePaths = new ArrayList<String>();
private int imageWidth;
public PhotosGridViewImageAdapter(Activity activity, ArrayList<String> filePaths,
int imageWidth) {
this._activity = activity;
this._filePaths = filePaths;
this.imageWidth = imageWidth;
}
#Override
public int getCount() {
return this._filePaths.size();
}
#Override
public Object getItem(int position) {
return this._filePaths.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
final ImageView imageView;
if (convertView == null) {
imageView = new ImageView(_activity);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(imageWidth,
imageWidth));
convertView = imageView;
holder = new ViewHolder();
holder.image = imageView;
holder.position = position;
convertView.setTag(holder);
} else {
//imageView = (ImageView) convertView;
holder = (ViewHolder) convertView.getTag();
((ImageView)convertView).setImageBitmap(null);
}
new AsyncTask<ViewHolder, Void, Bitmap>() {
private ViewHolder v;
// get screen dimensions
#Override
protected Bitmap doInBackground(ViewHolder... params) {
v = params[0];
Bitmap image = decodeFile(_filePaths.get(position), imageWidth,
imageWidth);
//imageView.setImageBitmap(image);
return image;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
v.image.setImageBitmap(result);
}
}.execute(holder);
return convertView;
}
/*
* Resizing image size
*/
public Bitmap decodeFile(String filePath, int WIDTH, int HEIGHT) {
try {
File f = new File(filePath);
if(filePath.contains(".jpg")) {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
final int REQUIRED_WIDTH = WIDTH;
final int REQUIRED_HEIGHT = HEIGHT;
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_WIDTH
&& o.outHeight / scale / 2 >= REQUIRED_HEIGHT)
scale *= 2;
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
}else if(filePath.contains(".mp4")){
return ThumbnailUtils.createVideoThumbnail(filePath, 0);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
class ViewHolder {
ImageView image;
int position;
}
}
Contextual action menu code
public class MultiChoiceModeListener implements
GridView.MultiChoiceModeListener {
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.contextual_action_menu, menu);
//mode.setTitle("Select Items");
mode.setTitle("1 item selected");
return true;
}
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return true;
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
// Respond to clicks on the actions in the CAB
switch (item.getItemId()) {
case R.id.delete:
SparseBooleanArray checked = gridView.getCheckedItemPositions();
try {
int len = checked.size();
for (int i = 0; i < len; i++) {
if (checked.valueAt(i)) {
Integer position = checked.keyAt(i);
//deleteToMessageHistory(position);
}
}
}catch (Exception i){
Toast.makeText(PhotosGridViewActivity.this, "Message was not deleted. Try again.", Toast.LENGTH_SHORT).show();
}
mode.finish(); // Action picked, so close the CAB
return true;
default:
return false;
}
}
public void onDestroyActionMode(ActionMode mode) {
}
public void onItemCheckedStateChanged(ActionMode mode, int position,
long id, boolean checked) {
int selectCount = gridView.getCheckedItemCount();
switch (selectCount) {
case 1:
mode.setTitle("1 item selected");
break;
default:
mode.setTitle("" + selectCount + " items selected");
break;
}
}
}
I appreciate any help!
==UPDATE==
Here is the MainActivity code:
public class PhotosGridViewActivity extends Activity {
private PhotosUtils utils;
private ArrayList<String> imagePaths = new ArrayList<String>();
private PhotosGridViewImageAdapter adapter;
private GridView gridView;
private int columnWidth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Initilizing Grid View
InitilizeGridLayout();
}
private void InitilizeGridLayout() {
setContentView(R.layout.photos_grid_view);
utils = new PhotosUtils(PhotosGridViewActivity.this);
gridView = (GridView) findViewById(R.id.grid_view);
// loading all image paths from SD card
imagePaths = utils.getFilePaths();
Resources r = getResources();
float padding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
AppConstant.GRID_PADDING, r.getDisplayMetrics());
columnWidth = (int) ((utils.getScreenWidth() - ((AppConstant.NUM_OF_COLUMNS + 1) * padding)) / AppConstant.NUM_OF_COLUMNS);
gridView.setNumColumns(AppConstant.NUM_OF_COLUMNS);
gridView.setColumnWidth(columnWidth);
gridView.setStretchMode(GridView.NO_STRETCH);
gridView.setPadding((int) padding, (int) padding, (int) padding,
(int) padding);
gridView.setHorizontalSpacing((int) padding);
gridView.setVerticalSpacing((int) padding);
gridView.setChoiceMode(GridView.CHOICE_MODE_MULTIPLE_MODAL);
gridView.setMultiChoiceModeListener(new MultiChoiceModeListener());
// Gridview adapter
adapter = new PhotosGridViewImageAdapter(PhotosGridViewActivity.this, imagePaths,
columnWidth);
// setting grid view adapter
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
gridView.getItemAtPosition(position);
Intent i = new Intent(PhotosGridViewActivity.this, PhotosScreenViewActivity.class);
i.putExtra("position", position);
PhotosGridViewActivity.this.startActivity(i);
}
});
}
public class MultiChoiceModeListener implements
GridView.MultiChoiceModeListener {
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.contextual_action_menu, menu);
//mode.setTitle("Select Items");
mode.setTitle("1 item selected");
return true;
}
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return true;
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
// Respond to clicks on the actions in the CAB
switch (item.getItemId()) {
case R.id.delete:
SparseBooleanArray checked = gridView.getCheckedItemPositions();
try {
int len = checked.size();
for (int i = 0; i < len; i++) {
if (checked.valueAt(i)) {
Integer position = checked.keyAt(i);
//deleteToMessageHistory(position);
}
}
}catch (Exception i){
Toast.makeText(PhotosGridViewActivity.this, "Message was not deleted. Try again.", Toast.LENGTH_SHORT).show();
}
mode.finish(); // Action picked, so close the CAB
return true;
default:
return false;
}
}
public void onDestroyActionMode(ActionMode mode) {
}
public void onItemCheckedStateChanged(ActionMode mode, int position,
long id, boolean checked) {
int selectCount = gridView.getCheckedItemCount();
switch (selectCount) {
case 1:
mode.setTitle("1 item selected");
break;
default:
mode.setTitle("" + selectCount + " items selected");
break;
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(co.glurl.appoid.R.menu.photo_gallery, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.add:
/** Go to the user's add photos. */
startActivity(new Intent(this, PhotoIntentActivity.class));
break;
//case R.id.settings:
/** Go to the user's settings photos. */
// startActivity(new Intent(this, PhotoGridSettings.class));
// break;
default:
return super.onContextItemSelected(item);
}
return true;
}
}
My soluction. Thanks to #pushbit for guiding me through it.
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ImageView imageView = (ImageView) convertView;
if (imageView == null) {
imageView = new ImageView(_activity);
}
// Trigger the download of the URL asynchronously into the image view.
if(_filePaths.get(position).contains(".jpg")) {
Picasso.with(_activity)
.load(new File(_filePaths.get(position)))
.resize(imageWidth, imageWidth)
.centerCrop()
.tag(_activity)
.into(imageView);
}else if(_filePaths.get(position).contains(".mp4")){
VideoRequestHandler videoRequestHandler;
Picasso picassoInstance;
videoRequestHandler=new VideoRequestHandler();
picassoInstance = new Picasso.Builder(_activity.getApplicationContext())
.addRequestHandler(videoRequestHandler)
.build();
picassoInstance
.load(videoRequestHandler.SCHEME_VIDEO+":"+_filePaths.get(position))
.resize(imageWidth, imageWidth)
.centerCrop()
.tag(_activity)
.into(imageView);
}
return imageView;
}
public static boolean deleteToPhotoAlbum(Integer position) {
File file = new File(_filePaths.get(position));
boolean deleted = file.delete();
return deleted;
}
public class VideoRequestHandler extends RequestHandler {
public String SCHEME_VIDEO = "video";
#Override
public boolean canHandleRequest(Request data)
{
String scheme = data.uri.getScheme();
return (SCHEME_VIDEO.equals(scheme));
}
#Override
public Result load(Request data, int arg1) throws IOException
{
Bitmap bm = ThumbnailUtils.createVideoThumbnail(data.uri.getPath(), MediaStore.Images.Thumbnails.MINI_KIND);
return new Result(bm, Picasso.LoadedFrom.DISK);
}
}

Categories