I want to share the current image being viewed from the viewflipper, but I can not get the name of the image being displayed, this is the code I use:
public class imagen1 extends Activity {
public float init_x;
private ViewFlipper vf;
int gallery_grid_Images[] = {R.drawable.fondo, R.drawable.fondo2, R.drawable.fondo3,
R.drawable.fondo4, R.drawable.fondo5
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.imagen1);
ImageView imagePreview = (ImageView) findViewById(R.id.preview);
vf = (ViewFlipper) findViewById(R.id.viewFlipper);
for (int i = 0; i < gallery_grid_Images.length; i++) {
// This will create dynamic image view and add them to ViewFlipper
setFlipperImage(gallery_grid_Images[i]);
}
vf.setOnTouchListener(new ListenerTouchViewFlipper());
}
private void setFlipperImage(int res) {
Log.i("Set Filpper Called", res + "");
ImageView image = new ImageView(getApplicationContext());
image.setBackgroundResource(res);
vf.addView(image);
}
public void compartir (View v) {
Uri newUri2 = Uri.parse("android.resource://" + getPackageName()
+ "/drawable/" + gallery_grid_Images);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_TEXT, "");
shareIntent.putExtra(Intent.EXTRA_STREAM, newUri2);
shareIntent.setType("image/jpg");
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(shareIntent, "Compartir"));
}
}
If someone could help me a little would greatly appreciate it
Probably this should do the trick for you:
public class imagen1 extends Activity {
public float init_x;
private ViewFlipper vf;
int gallery_grid_Images[] = {R.drawable.fondo, R.drawable.fondo2, R.drawable.fondo3,
R.drawable.fondo4, R.drawable.fondo5
};
ImageView[] views = new ImageView[gallery_grid_Images.length];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.imagen1);
ImageView imagePreview = (ImageView) findViewById(R.id.preview);
vf = (ViewFlipper) findViewById(R.id.viewFlipper);
for (int i = 0; i < gallery_grid_Images.length; i++) {
// This will create dynamic image view and add them to ViewFlipper
setFlipperImage(gallery_grid_Images[i], i);
}
vf.setOnTouchListener(new ListenerTouchViewFlipper());
}
private void setFlipperImage(int res, int index) {
Log.i("Set Filpper Called", res + "");
ImageView image = new ImageView(getApplicationContext());
image.setBackgroundResource(res);
vf.addView(image);
views[index] = image;
}
public void compartir (View v) {
int index = -1;
for (int i = 0; i < views.length; i++) {
if (views[i] == (ImageView) vf.getCurrentView())
index = i;
}
if (index == -1) {
// failed to determine the right index
Log.w("imagen1", "Could not determine the right index!");
return;
}
Uri newUri2 = Uri.parse("android.resource://" + getPackageName()
+ "/drawable/" + gallery_grid_Images[index]);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_TEXT, "");
shareIntent.putExtra(Intent.EXTRA_STREAM, newUri2);
shareIntent.setType("image/jpg");
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(shareIntent, "Compartir"));
}
}
I've used it just a few times, but as far as I know the viewflipper just show one of its childs at a time. You should call this method in order to show a child:
viewFlipper.setDisplayedChild(childPosition);
The loop in your code will just set the last image of your array, if you'd rather to show a list of images you should go for a RecyclerView/ListView.
Hope this helps!
works perfectly, you do not know how much I appreciate your help, I only had to modify a part in the code because it gave me error:
Uri newUri2 = Uri.parse("android.resource://" + getPackageName()
+ "/drawable/" + gallery_grid_Images[i]);
add Index
Uri newUri2 = Uri.parse("android.resource://" + getPackageName()
+ "/drawable/" + gallery_grid_Images[index]);
Thank you so much for your help
Related
I have a RecyclerView in my project that shows a list of ticket messages.
I use pagination to show the messages in parts. I think notifyDataSetChange is the method I should use to add newly added items.
Below is the code for how I handle adding new items to my list:
public void makeList(List<SingleTicketModel> ticketMessages) {
for (int i = 0; i < ticketMessages.size(); i++) {
ticket.add(
new TicketItemModel(
ticketMessages.get(i).getContent(),
ticketMessages.get(i).getCreatedAt(),
ticketMessages.get(i).getDirection(),
ticketMessages.get(i).getAgentName(),
ticketMessages.get(i).getAttachment()
)
);
}
if (ticketAdaptor == null) {
ticketAdaptor = new TicketAdaptor(getApplicationContext(), ticket, this);
recyclerView.setAdapter(ticketAdaptor);
linearLayoutManager = new LinearLayoutManager(getApplicationContext());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setVisibility(View.VISIBLE);
recyclerView.addOnScrollListener(new EndlessRecyclerOnScrollListener(linearLayoutManager) {
#Override
public void onLoadMore(int current_page) {
loadMoreProgressBar.setVisibility(View.VISIBLE);
getTickets(loginToken, current_page,ticketID);
}
});
progressBar.setVisibility(View.GONE);
} else {
ticketAdaptor.notifyDataSetChanged();
}
There may be an attachment in some messages and here is my problem:
When a user clicks on attachment button, the button is being converted to a progressBar as long as the attachment is downloaded.
But If the user clicks on attachment icon, all attachment icons in the list turn into progressBar and this means that setOnClickListener method executes on all items!
The important thing is that this happens only if notifyDataSetChange method is called.
I conclude that if the number of messages is low and there is no need to load more information, this will not happen.
In addition, another point that I think is related to this problem:
If the user clicks the attachment button (in which case the imageButton image changes after the download is complete), It seems that the item will be rebuilt by scrolling the list and the attachment button image will return to the first state.(again after new data is being added to the list)
here is my adaptor file :
public class TicketAdaptor extends RecyclerView.Adapter<TicketAdaptor.ViewHolder> {
private Context context;
private Activity activity;
private List<TicketItemModel> ticket;
View view;
public TicketAdaptor(Context context, List<TicketItemModel> ticket, Activity activity){
this.context = context;
this.ticket = ticket;
this.activity = activity;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
this.view = LayoutInflater.from(this.context).inflate(R.layout.ticket_item_in, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.ticketDescription.setText(ticket.get(position).getContent());
holder.ticketDate.setText(ticket.get(position).getCreatedAt());
switch (holder.getItemViewType()){
case 1 :
holder.itemView.setBackgroundResource(R.drawable.radius_background_gray);
holder.ticketDate.setBackgroundResource(R.drawable.radius_background_light_gray);
holder.ticketStatus.setImageResource(R.drawable.ic_attachment_black_24dp);
break;
case 11 :
holder.itemView.setBackgroundResource(R.drawable.radius_background_gray);
holder.ticketDate.setBackgroundResource(R.drawable.radius_background_light_gray);
break;
case 3 :
holder.ticketStatus.setImageResource(R.drawable.ic_attachment_black_24dp);
break;
default: break;
}
holder.ticketTitle.setText(ticket.get(position).getAgentName() + " said :");
holder.ticketStatus.setOnClickListener(new View.OnClickListener() {
boolean counter = false;
#Override
public void onClick(View v) {
if (requestPermission() == true) {
File attachmentFile = new File((Environment.getExternalStorageDirectory()
+ "/"
+ context.getResources().getString(R.string.app_name)
+ "/"
+ context.getResources().getString(R.string.ticket_directory)
+ "/"
+ ticket.get(position).getCreatedAt().replaceAll("\\s|:|-","") + ".jpeg" ));
if( !counter && !attachmentFile.exists())
{
holder.attachmentProgressBar.setVisibility(View.VISIBLE);
holder.ticketStatus.setVisibility(View.GONE);
downloadAttachment(ticket.get(position)
.getAttachment(),
ticket
.get(position)
.getCreatedAt()
.replaceAll("\\s|:|-","") + ".jpeg",
holder.ticketStatus,holder.attachmentProgressBar);
counter = true;
}else{
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
File file = new File((Environment.getExternalStorageDirectory()
+ "/"
+ context.getResources().getString(R.string.app_name)
+ "/"
+ context.getResources().getString(R.string.ticket_directory)),
ticket.get(position).getCreatedAt().replaceAll("\\s|:|-","")
+ ".jpeg"
);
intent.setDataAndType(FileProvider.getUriForFile(context,
BuildConfig.APPLICATION_ID + ".provider",
file),"image/*");
activity.startActivity(intent);
}
}
}
});
}
#Override
public int getItemViewType(int position) {
String Direction = ticket.get(position).getDirection();
String Attachment = ticket.get(position).getAttachment();
if(Direction.equals("out")){
if (Attachment != null)
return 1;
else return 11;
}else if(!(Direction.equals("out"))){
if(Attachment != null)
return 3;
}
return 0;
}
#Override
public int getItemCount() {
return ticket.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
TextView ticketTitle;
TextView ticketDescription;
TextView ticketDate;
ImageView ticketStatus;
ProgressBar attachmentProgressBar;
public ViewHolder(View itemView) {
super(itemView);
this.ticketTitle = itemView.findViewById(R.id.ticket_agent);
this.ticketDescription = itemView.findViewById(R.id.ticket_description);
this.ticketDate = itemView.findViewById(R.id.ticket_date);
this.ticketStatus = itemView.findViewById(R.id.ticket_attachment);
this.attachmentProgressBar = itemView.findViewById(R.id.attachment_progressbar);
attachmentProgressBar.setVisibility(View.GONE);
}
}
private void downloadAttachment(String url, final String imageName, final View attachmentIcon, final View attachmentProgressBar){
APIInterface apiInterface = APIClient.getClient().create(APIInterface.class);
Call<ResponseBody> call = apiInterface.getAttachment(url);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
saveAttachment saveAttachment = new saveAttachment(imageName,attachmentIcon, attachmentProgressBar);
saveAttachment.execute(response.body().byteStream());
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
}
private class saveAttachment extends AsyncTask<InputStream,Void,Boolean>{
private String imageName;
private View attachmentIcon;
private View attachmentProgressBar;
public saveAttachment(String imageName, View attachmentIcon, View attachmentProgressBar) {
super();
this.imageName = imageName;
this.attachmentIcon = attachmentIcon;
this.attachmentProgressBar = attachmentProgressBar;
}
#Override
protected Boolean doInBackground(InputStream... inputStreams) {
InputStream inputStream = inputStreams[0];
final File directory = new File((Environment.getExternalStorageDirectory()
+ "/"
+ context.getResources().getString(R.string.app_name)
+ "/"
+ context.getResources().getString(R.string.ticket_directory)
));
if (!directory.exists())
directory.mkdirs();
final File myImageFile = new File(directory, imageName);
OutputStream outputStream = null;
try {
outputStream = new FileOutputStream(myImageFile);
byte [] buffer = new byte[2048];
int read;
while ((read = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, read);
}
outputStream.flush();
outputStream.close();
}catch (IOException e){}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
attachmentProgressBar.setVisibility(View.GONE);
((ImageView) attachmentIcon).setImageResource(R.drawable.ic_slow_motion_video_black_24dp);
attachmentIcon.setVisibility(View.VISIBLE);
}
}
}
(I removed some of the code that did not relate to the topic.)
I am not sure but this could be a problem from mismatched positions, since you are adding more to the list. I would suggest setting your OnClickListener on the ViewHolder constructor. The position parameter on the onBindViewHolder method should not be treated as static (when used in anonymous classes like your listener). See if things get better.
Also, you could use notifyItemChanged to just change the one clicked like:
notifyItemChanged(getAdapterPosition());
inside your click listener callback.
So, your code would get more like this:
public ViewHolder(View itemView) {
super(itemView);
this.ticketTitle = itemView.findViewById(R.id.ticket_agent);
this.ticketDescription = itemView.findViewById(R.id.ticket_description);
this.ticketDate = itemView.findViewById(R.id.ticket_date);
this.ticketStatus = itemView.findViewById(R.id.ticket_attachment);
this.attachmentProgressBar = itemView.findViewById(R.id.attachment_progressbar);
attachmentProgressBar.setVisibility(View.GONE);
ticketStatus.setOnClickListener(new View.OnClickListener() {
boolean counter = false;
#Override
public void onClick(View v) {
if (requestPermission() == true) {
File attachmentFile = new File((Environment.getExternalStorageDirectory()
+ "/"
+ context.getResources().getString(R.string.app_name)
+ "/"
+ context.getResources().getString(R.string.ticket_directory)
+ "/"
+ ticket.get(getAdapterPosition()).getCreatedAt().replaceAll("\\s|:|-","") + ".jpeg" ));
if (!counter && !attachmentFile.exists()) {
attachmentProgressBar.setVisibility(View.VISIBLE);
ticketStatus.setVisibility(View.GONE);
downloadAttachment(ticket.get(getAdapterPosition()).getAttachment(),
ticket.get(getAdapterPosition()).getCreatedAt().replaceAll("\\s|:|-","") + ".jpeg",
ticketStatus, attachmentProgressBar);
counter = true;
// Update UI only for this item.
notifyItemChanged(getAdapterPosition());
} else {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
File file = new File((Environment.getExternalStorageDirectory()
+ "/"
+ context.getResources().getString(R.string.app_name)
+ "/"
+ context.getResources().getString(R.string.ticket_directory)),
ticket.get(getAdapterPosition()).getCreatedAt().replaceAll("\\s|:|-","")
+ ".jpeg"
);
intent.setDataAndType(FileProvider.getUriForFile(context,
BuildConfig.APPLICATION_ID + ".provider",
file),"image/*");
activity.startActivity(intent);
}
}
}
});
I'm making a gallery in my application. I listed my images successfully and now adding its share buttons. Instead of directing user into another form, I'm trying to show share buttons above my image. For listing and sharing I need to create and add dynamic ImageButtons. But when I try to add share buttons, they're shown in wrong place. Here is my code:
LinearLayout ll = (LinearLayout) findViewById(R.id.llGallery);
for (int i = 0; i < jsonArray.length(); i++) {
final JSONObject jsonObject = jsonArray.getJSONObject(i);
final String Photo= jsonObject.getString("PhotoLink");
// PhotoDetails into another view
View.OnClickListener cPhotoDetails= new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(GalleryDetailsActivity.this,
GalleryPhotoDetails.class);
intent.putExtra("Image", Photo);
startActivity(intent);
}
};
View.OnClickListener cShare= new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
File myFile = new File(fotograf);
MimeTypeMap mime = MimeTypeMap.getSingleton();
String ext = myFile.getName().substring(myFile.getName().lastIndexOf(".") + 1);
String type = mime.getMimeTypeFromExtension(ext);
Intent sharingIntent = new Intent("android.intent.action.SEND");
sharingIntent.setType(type);
sharingIntent.putExtra("android.intent.extra.STREAM", Uri.fromFile(myFile));
startActivity(Intent.createChooser(sharingIntent, "Share with"));
} catch (Exception e) {
// Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
};
RelativeLayout rel = new RelativeLayout(context);
rel.setGravity(Gravity.CENTER_VERTICAL);
ImageButton img = new ImageButton(context);
img.setClickable(true);
img.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
Glide.with(context).load(Photo).into(img);
img.setOnClickListener(cPhotoDetails);
rel.addView(img);
ImageButton share = new ImageButton(context);
share.setClickable(true);
share.setScaleType(ImageView.ScaleType.FIT_XY);
Glide.with(context).load(R.drawable.btn_share).into(share);
share.setOnClickListener(cShare);
rel.addView(share);
ll.addView(rel);
}
RelativeLayout rel = new RelativeLayout(context);
rel.setGravity(Gravity.CENTER_VERTICAL);
ImageView img = new ImageView(context);
img.setClickable(true);
img.setScaleType(ImageView.ScaleType.FIT_XY);
Glide.with(context).load(Photo).into(img);
img.setOnClickListener(cPhotoDetails);
rel.addView(img);
ImageButton share = new ImageButton(context);
share.setClickable(true);
share.setScaleType(ImageView.ScaleType.FIT_XY);
Glide.with(context).load(R.drawable.btn_share).into(share);
share.setOnClickListener(cShare);
rel.addView(share);
ll.addView(rel);
I have an app in which I have to combine parts of clothes. To understand me better I have given a screenshot below. The thing is, that i am having problems on how to get these images and save them in my database. Of course i faced errors.
public class ViewOutfit extends Activity {
private DatabaseHandler handler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_outfit);
Intent i = getIntent();
final ImageView im1 = (ImageView) findViewById(R.id.im1);
im1.setImageBitmap(BitmapFactory.decodeFile(i.getStringExtra("image1")));
im1.toString();
final ImageView im2 = (ImageView) findViewById(R.id.im2);
im2.setImageBitmap(BitmapFactory.decodeFile(i.getStringExtra("image2")));
im2.toString();
final ImageView im3 = (ImageView)findViewById(R.id.im3);
im3.setImageBitmap(BitmapFactory.decodeFile(i.getStringExtra("image3")));
im3.toString();
final ImageView im4 = (ImageView)findViewById(R.id.im4);
im4.setImageBitmap(BitmapFactory.decodeFile(i.getStringExtra("image4")));
im4.toString();
final ImageView im5 = (ImageView)findViewById(R.id.im5);
im5.setImageBitmap(BitmapFactory.decodeFile(i.getStringExtra("image5")));
im5.toString();
final ImageView im6 = (ImageView)findViewById(R.id.im6);
im6.setImageBitmap(BitmapFactory.decodeFile(i.getStringExtra("image6")));
im6.toString();
ImageButton btn_save_outfit = (ImageButton)findViewById(R.id.btn_combine);
btn_save_outfit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
im1.getDrawable().toString();
im2.getDrawable().toString();
im3.getDrawable().toString();
im4.getDrawable().toString();
im5.getDrawable().toString();
im6.getDrawable().toString();
Outfits outfits = new Outfits();
outfits.setImage1(String.valueOf(im1));
outfits.setImage2(String.valueOf(im2));
outfits.setImage3(String.valueOf(im3));
outfits.setImage4(String.valueOf(im4));
outfits.setImage5(String.valueOf(im5));
outfits.setImage6(String.valueOf(im6));
Boolean added = handler.addOutfit(outfits);
if(added){
Toast.makeText(getApplicationContext() , "Outfit added." , Toast.LENGTH_LONG).show();
String log = "Id: "+ outfits.getID()+" ,Image1: " + outfits.getImage1() + " ,Image2: " + outfits.getImage2()
+ ",Image3:" + outfits.getImage3() + ",Image4:" + outfits.getImage5() + ",Image6:" +outfits.getImage6();
Log.d("Image1: ", log);
}else{
Toast.makeText(getApplicationContext(), "Outfit not added. Please try again", Toast.LENGTH_LONG).show();
}
}});
}
I want to show image from camera in HorizontalScrollView Images.
Currently, In each item of List View HorizontalScrollView is added and each
HorizontalScrollView displayes the images dynamically on the basis of data fetched from the sqlite. Sqlite is preloaded with the data that is downloaded from our application server.
Also, In each list item 'Camera' button is added. On click event of this button .I am adding images captured from Camera to the existing HorizontalScrollView.
I am adding some code snippet from my application -
1) First I'm trying to show images dynamically in HorizontalScrollView from sqlite in ArrayAdapter -
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View row = convertView;
final Holder holder;
if (row == null)
{
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
row = vi.inflate(R.layout.all_post_row, null);
holder = new Holder();
holder.horizontalScrollView = (HorizontalScrollView)row.findViewById(R.id.hlist);
holder.lLinearLayout=(LinearLayout)row.findViewById(R.id.innerlay);
row.setTag(holder);
}
else
{
holder = (Holder) row.getTag();
}
final All_Post all_Post = data.get(position);
String strListItem_ActivityId = all_Post.getStrActivityId();
Log.e("strListItem_ActivityId ", " = " + strListItem_ActivityId);
dbhelper = new MyDbHelper(AllPosts_Page.this);
SQLiteDatabase db = dbhelper.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from ActivityObjectList where activityId " + "= ? ", new String[]{strListItem_ActivityId});
imageArray.clear();
if (cursor.moveToFirst())
{
do
{
String imagePath = cursor.getString(cursor.getColumnIndex("imageaudioPath"));
Log.e("imagePath ", " = " + imagePath);
imageArray.add(imagePath);
}
while (cursor.moveToNext());
}
cursor.close();
db.close();
holder.lLinearLayout.removeAllViews();
final Iterator<String> it = imageArray.iterator();
while (it.hasNext())
{
final String imgElement = it.next();
int imgArraySize = imageArray.size();
Log.e("imgArraySize "," = " + imgArraySize);
final ImageView imageView = new ImageView (getContext());
final ProgressBar pBar = new ProgressBar(getContext(),null ,android.R.attr.progressBarStyleSmall);
imageView.setTag(it);
pBar.setTag(it);
imageView.setImageResource(R.drawable.img_placeholder);
pBar.setVisibility(View.VISIBLE);
Uri uri = Uri.fromFile(new File(path));
Picasso.with(getContext()).load(uri).placeholder(R.drawable.img_placeholder).resize(newWidth,fixHeight).into(imageView, new com.squareup.picasso.Callback() {
#Override
public void onSuccess() {
if (pBar != null) {
pBar.setVisibility(View.GONE);
}
}
#Override
public void onError() {
}
});
holder.lLinearLayout.addView(imageView);
holder.lLinearLayout.addView(pBar);
}
2) 2) Here is my Camera button click event in ArrayAdapter class -
holder.imgBtn_Camera.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(context, "Camera" + " = ", Toast.LENGTH_SHORT).show();
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
}
});
3) Here is onActivityResult method implementation which is in Activity class -
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_PIC_REQUEST)
{
activityObj_Id++;
intoString = Integer.toString(activityObj_Id);
SimpleDateFormat s = new SimpleDateFormat("ddMMyyyyhhmmss");
String dateformat = s.format(new Date());
Log.e("format", " and activityObj_Id = " + dateformat + " & " + activityObj_Id);
imageCamera_Path = activityObj_Id +"_"+ dateformat+".png";
downloadstatus = "1";
Log.e("imageCamera_Path", "= " + imageCamera_Path);
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
//imageView.setImageBitmap(thumbnail);
}
Log.e("Data Save","in onActivityResult Succesfully !!!!");
}
The above code should show the images captured from camera into HorizontalScrollView. However, images are not getting added to scroll view. I am not able to understand where does it went wrong ? I have tried to modify code in many ways. However it did not help.
Please take look at my code snippets and let me know if anything is missing.
Thanks.
My application is able to take pictures and to save and to show them in a list. They also can be deleted and the list is correctly updated.
However, if I close the application and then launch it again, the list is no more correct. In detail:
These are the list elements in the adapter after I take two pictures:
List[0] 20150603_042556
List[1] 20150603_042601
These pictures are correctly saved. However, if I close and open again the application, this is what happens:
Loaded selfie:﹕ 20150603_042556
List[0] 20150603_042556
Loaded selfie: 20150603_042601
List[0] 20150603_042601
List[1] 20150603_042601
This is the add function:
public void add(SelfieRecord listItem) {
list.add(listItem);
for(int k=0;k<list.size();k++)
Log.i("List: ", String.valueOf(k) + " " + list.get(k).getPicName());
notifyDataSetChanged();
}
This is how I load the saved pictures:
for (int ii = 0; ii < dirFiles.length; ii++) {
File file = dirFiles[ii];
String path = file.getAbsolutePath();
selfie.setPic(path);
selfie.setPicName(path.substring(path.indexOf("_") + 1, path.lastIndexOf("_")));
Log.i(TAG+" Loaded selfie: ",path);
mAdapter.add(selfie);
}
Can't figure out what happens.
EDIT: More code follows.
In the main activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// setup notifications
setNotifications();
mListView = (ListView)findViewById(R.id.selfieList);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, ViewActivity.class);
SelfieRecord record = (SelfieRecord) mAdapter.getItem(position);
intent.putExtra(SELFIE_KEY, record.getPic());
startActivity(intent);
}
});
mAdapter = new SelfieAdapter(getApplicationContext());
mListView.setAdapter(mAdapter);
// load selfies
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) && mAdapter.getCount()==0) {
// gets the files in the directory
File fileDirectory = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath());
if (!fileDirectory.exists()) {
fileDirectory.mkdirs();
}
// lists all the files into an array
File[] dirFiles = fileDirectory.listFiles();
if (dirFiles.length != 0) {
SelfieRecord selfie = new SelfieRecord();
// loops through the array of files, outputing the name to console
for (int ii = 0; ii < dirFiles.length; ii++) {
File file = dirFiles[ii];
String path = file.getAbsolutePath();
selfie.setPic(path);
selfie.setPicName(path.substring(path.indexOf("_") + 1, path.lastIndexOf("_")));
Log.i(TAG+" Loaded selfie: ",path);
mAdapter.add(selfie);
}
}
}
registerForContextMenu(mListView);
}
In the Adapter:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View newView = convertView;
ViewHolder holder;
SelfieRecord curr = list.get(position);
Log.i("List: ", String.valueOf(position)+" "+list.get(position).getPicName());
if (null == convertView) {
holder = new ViewHolder();
newView = inflater.inflate(R.layout.list_record, parent, false);
holder.pic = (ImageView) newView.findViewById(R.id.pic);
holder.name = (TextView) newView.findViewById(R.id.pic_name);
newView.setTag(holder);
} else {
holder = (ViewHolder) newView.getTag();
}
//setPic(holder.pic, curr.getPic());
holder.name.setText(curr.getPicName());
mImageView = holder.pic;
new BitmapLoader().execute(curr.getPic());
Log.i("Loader: ", String.valueOf(position) + " " + curr.getPicName());
return newView;
}
static class ViewHolder {
ImageView pic;
TextView name;
}
public void add(SelfieRecord listItem) {
list.add(listItem);
for(int k=0;k<list.size();k++)
Log.i("List: ", String.valueOf(k) + " " + list.get(k).getPicName());
notifyDataSetChanged();
}
public void remove(int position) {
list.remove(position);
notifyDataSetChanged();
}
Bitmap Loader:
public class BitmapLoader extends AsyncTask<String,Integer,Bitmap> {
#Override
protected Bitmap doInBackground(String... resId) {
// Get the dimensions of the View
int targetW = Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 160, mContext.getResources().getDisplayMetrics()));
int targetH = Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 120, mContext.getResources().getDisplayMetrics()));
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(resId[0], bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW/targetW, photoH/targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(resId[0], bmOptions);
return bitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
mImageView.setImageBitmap(result);
}
}
I believe the problem is when I put the elements in the adapter after recovered them from storage:
Loaded selfie:﹕ 20150603_042556
List[0] 20150603_042556
Loaded selfie: 20150603_042601
List[0] 20150603_042601
List[1] 20150603_042601
The second call to the adapter's add method overwrite the first element. Why?
Solved by changing the for loop in on Create:
if (dirFiles.length != 0) {
// loops through the array of files, outputing the name to console
for (int ii = 0; ii < dirFiles.length; ii++) {
File file = dirFiles[ii];
String path = file.getAbsolutePath();
SelfieRecord selfie = new SelfieRecord();
selfie.setPic(path);
selfie.setPicName(path.substring(path.indexOf("_") + 1, path.lastIndexOf("_")));
Log.i(TAG+" Loaded selfie: ",path);
mAdapter.add(selfie);
}
}
Must pass a different SelfieRecord Object to the add method.