I have a list view with image.I want to change list item image on onActivityResult
of image capturing .I get the image file bitmap but when I change the list items image the list view image does not change.
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);
imageView1.setImageBitmap(bitmap);//there a bitmap exist---
dataAdapter.taskList.get(0).setImgBitmap(bitmap);
//this is not changing list image.why???????
dataAdapter.notifyDataSetChanged();
here the imageview1 has a bitmap and I set it to first item of list using CustomAdapter class's ArrayList<Task> taskList parameter.
here full sample code
NotifyAcitivity.java
package com.aci.notification;
public class NotifyActivity extends Activity {
// Activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
public static final int MEDIA_TYPE_IMAGE = 1;
// directory name to store captured images and videos
private static final String IMAGE_DIRECTORY_NAME = "Hello Camera";
private Uri fileUri; // file url to store image/video
private ImageView imageView1;
Bitmap bm, bm2;
private Button btnCapturePicture;
ArrayList<Task> taskList = new ArrayList<Task>();
TextView tv;
CustomAdapter dataAdapter = null;
Button btnSave;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notify);
btnCapturePicture = (Button) findViewById(R.id.btnCapturePicture);
imageView1 = (ImageView) findViewById(R.id.imageView1);
tv = (TextView) findViewById(R.id.textViewtest);
btnSave = (Button) findViewById(R.id.button1);
listView = (ListView) findViewById(R.id.listView1);
new BitmapFactory();
bm = BitmapFactory.decodeResource(getApplicationContext()
.getResources(), R.drawable.ic_launcher);
bm2 = BitmapFactory.decodeResource(getApplicationContext()
.getResources(), R.drawable.bydefault);
Task task;
task = new Task(0, "This is task1", "/pictures/hello camera/", bm,false);
taskList.add(task);
task = new Task(1, "This is task2", "/pictures/hello camera/", bm,false);
taskList.add(task);
task = new Task(0, "This is task3", "/pictures/hello camera/", bm,false);
taskList.add(task);
task = new Task(0, "This is task4", "/pictures/hello camera/", bm2,false);
taskList.add(task);
task = new Task(0, "This is task5", "/pictures/hello camera/", bm,false);
taskList.add(task);
dataAdapter = new CustomAdapter(this, R.layout.list_style, taskList);
listView.setAdapter(dataAdapter);
}
/**
* Receiving activity result method will be called after closing the camera
* */
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// successfully captured the image
// display it in image view
previewCapturedImage();
}
}
}
/**
* Display image from a path to ImageView
*/
private void previewCapturedImage() {
try {
imageView1.setVisibility(View.VISIBLE);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);
imageView1.setImageBitmap(bitmap);
dataAdapter.taskList.get(0).setImgBitmap(bitmap);
dataAdapter.notifyDataSetChanged();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
}
CustomAdapter.java
public class CustomAdapter extends ArrayAdapter<Task> {
public ArrayList<Task> taskList;
Context context;
public CustomAdapter(Context context, int resource, ArrayList<Task> taskList) {
super(context, resource, taskList);
this.context=context;
// TODO Auto-generated constructor stub
this.taskList = new ArrayList<Task>();
this.taskList.addAll(taskList);
}
private class ViewHolder {
CheckBox task;
ImageView imageView;
int task_id;
Button imageCaptureBtnButton;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder viewHolder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null) {
LayoutInflater vi =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.list_style, null);
viewHolder = new ViewHolder();
viewHolder.task_id=taskList.get(position).getTask_id();//set task id of that task
viewHolder.task = (CheckBox) convertView.findViewById(R.id.checkBox1);
viewHolder.imageView=(ImageView) convertView.findViewById(R.id.imgPreview);
viewHolder.imageCaptureBtnButton=(Button) convertView.findViewById(R.id.btnCapturePicture);
viewHolder.imageView.setImageBitmap(taskList.get(position).getImgBitmap());
convertView.setTag(viewHolder);
viewHolder.task.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
Task aTask =(Task) cb.getTag();
Toast.makeText(context,
"Clicked on Checkbox: " + cb.getText() + " is "
+ cb.isChecked(), Toast.LENGTH_LONG).show();
aTask.setSelected(cb.isChecked());
}
});
viewHolder.imageCaptureBtnButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "dddd", Toast.LENGTH_LONG).show();
}
});
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
Task aTask = taskList.get(position);
viewHolder.task.setText(taskList.get(position).getTask());
viewHolder.task.setChecked(taskList.get(position).isSelected());
viewHolder.task.setTag(aTask);
return convertView;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public int getCount() {
return taskList.size();
}
#Override
public Task getItem(int arg0) {
return null;
}
}
Task.java
public class Task {
int task_id = 0;
String task = null;
String imageURL=null;
Bitmap imgBitmap;
boolean selected=false;
public Task(int task_id, String task, String imageURL,Bitmap imgBitmap, boolean selected) {
super();
this.task_id = task_id;
this.task= task;
this.imageURL=imageURL;
this.imgBitmap=imgBitmap;
this.selected = selected;
}
//all getters and setters here
}
I have lost my days .please help me.
After a long time I found my own question answer.
The code is not fully matched to this question because answer is from my another project.I am just giving the way I succeeded.
Step 1:
When an image is captured I call imagedata(Bitmap bitmap).It convert each bitmap to base_64 string and this method adds new image to a list as array element of type ByteDrawable.
I create new adapter object again and set that adapter to the
listview.
private void imagedata(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Must compress the Image to reduce image size to make upload easy
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byte_arr = stream.toByteArray();
// Encode Image to String
image_data = Base64.encodeToString(byte_arr, 0);
byteDrawableList.add(new ByteDrawable(image_data));
listAdapter = new CustomAdapter(this);
listView.setAdapter(listAdapter );
}
public class ByteDrawable {
String imageAsBytes;
public ByteDrawable(String imageAsBytes) {
this.imageAsBytes = imageAsBytes;
}
}
Step 2:
Then I populate my list from that arraylist and in Adapter class's constructor I convert the base_64 string to bitmap and add element to a local arraylist items<Item>, then in getview() method I used items to create listview.
private class CustomAdapter extends ArrayAdapter<ByteDrawable>{
public CustomAdapter(Context context, int resource, ArrayList<ByteDrawable > byteDrawableList) {
super(context, resource, byteDrawableList);
this.context=context;
this.byteDrawableList= new ArrayList<ByteDrawable >();
this.byteDrawableList.addAll(byteDrawableList);
inflater = LayoutInflater.from(context);
long k = 0;
for (ByteDrawable bd : byteDrawableList) {
String base = bd.getImageByteString();
byte[] imageAsBytes = Base64.decode(base.getBytes(),
Base64.DEFAULT);
items.add(new Item(k, BitmapFactory.decodeByteArray(
imageAsBytes, 0, imageAsBytes.length)));
k++;
}
}
private class Item {
final long itmeid;
final Bitmap drawabledata;
Item(long id, Bitmap bitmap) {
this.itmeid = id;
this.drawabledata = bitmap;
}
}
public View getView(final int position, View view, ViewGroup viewGroup) {
/* follow normal way to set data to list item*/
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int i) {
return items.get(i);
}
#Override
public long getItemId(int i) {
return items.get(i).itmeid;
}
}
Hope this will help someone if they face same problem.
Related
I have an activity with a capture button this catpture button when clicked ,it prompts the user with an alert dialog asking to choose between gallery and camera after making the decision and capturing the image or choosing it the app currently save the image in an image view,now how can i save the images in a gridview in another activity rather than the imageview,and as much as possible avoiding using sqlite?!
mainactivity.java:
public static final int CAMERA_PERM_CODE = 101;
public static final int CAMERA_REQUEST_CODE = 102;
public static final int GALLERY_REQUEST_CODE = 105;
DatabaseHelper mDatabaseHelper;
Cursor data;
Cursor price;
ArrayList<myDataClass> listData;
ArrayAdapter adapter;
ArrayList arrayList;
public SwipeMenuListView mListview;
CustomAdapter custom;
private TextView total;
ImageView camera;
ImageView display1;
String currentPhotoPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listitemsbought);
getSupportActionBar().hide();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
mListview = (SwipeMenuListView) findViewById(R.id.list_items_bought);
mDatabaseHelper = new DatabaseHelper(this);
data = mDatabaseHelper.getDataOfTable();
total = (TextView) findViewById(R.id.totalpriceofitems);
listData = new ArrayList<myDataClass>();
camera = (ImageView) findViewById(R.id.imagetopic);
display1 = (ImageView) findViewById(R.id.displayimage);
display1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Listitemsbought.this,savedPics.class);
overridePendingTransition(R.anim.slide_in,R.anim.slide_out);
startActivity(intent);
}
});
camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
askCameraPermission();
}
});
// adapter = new ArrayAdapter<String>(this, R.layout.list_boughts,R.id.Name,listData);
populateListView();
final SwipeMenuCreator creator = new SwipeMenuCreator() {
#Override
public void create(SwipeMenu menu) {
// create "delete" item
SwipeMenuItem deleteItem = new SwipeMenuItem(
getApplicationContext());
// set item background
deleteItem.setBackground(new ColorDrawable(Color.rgb(0,
0, 0)));
// set item width
deleteItem.setWidth((250));
// set a icon
deleteItem.setIcon(R.drawable.sym_keyboard_delete_holo_dark);
// add to menu
menu.addMenuItem(deleteItem);
}
};
// set creator
mListview.setMenuCreator(creator);
// Left
mListview.setSwipeDirection(SwipeMenuListView.DIRECTION_LEFT);
}
private void askCameraPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,new String[] {Manifest.permission.CAMERA}, CAMERA_PERM_CODE);
}else {
alert();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == CAMERA_PERM_CODE){
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
alert();
}
}else {
Toast.makeText(this,"Camera Permission is required to use camera.",Toast.LENGTH_SHORT).show();
}
}
private void alert() {
new AlertDialog.Builder(Listitemsbought.this)
.setTitle(null)
.setMessage("Do you want to open gallery or take a new photo")
// Specifying a listener allows you to take an action before dismissing the dialog.
// The dialog is automatically dismissed when a dialog button is clicked.
.setPositiveButton("Open Camera", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dispatchTakePictureIntent();
}
})
// A null listener allows the button to dismiss the dialog and take no further action.
.setNegativeButton("Gallery", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent gallery = new Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(gallery, GALLERY_REQUEST_CODE);
}
})
.setIcon(android.R.drawable.ic_menu_camera)
.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if(requestCode == CAMERA_REQUEST_CODE){
if(resultCode == Activity.RESULT_OK){
File f = new File(currentPhotoPath);
display1.setImageURI(Uri.fromFile(f));
Log.d("tag", "ABsolute Url of Image is " + Uri.fromFile(f));
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
}
if(requestCode == GALLERY_REQUEST_CODE){
if(resultCode == Activity.RESULT_OK){
Uri contentUri = data.getData();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp +"."+getFileExt(contentUri);
Log.d("tag", "onActivityResult: Gallery Image Uri: " + imageFileName);
display1.setImageURI(contentUri);
}
}
}
private String getFileExt(Uri contentUri) {
ContentResolver c = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(c.getType(contentUri));
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
// File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = image.getAbsolutePath();
return image;
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.medicnes.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
}
}
}
private void populateListView(){
while (data.moveToNext()){
listData.add(new myDataClass(data.getString(data.getColumnIndex("Name")),data.getString(data.getColumnIndex("Amount")),data.getString(data.getColumnIndex("Price"))));
}
total.setText(mDatabaseHelper.getPriceSum());
custom = new CustomAdapter(listData, this);
mListview.setAdapter(custom);
//custom.notifyDataSetChanged();
}
public class CustomAdapter extends BaseAdapter
{
private Context context;
private List<String> strings;
public class ViewHolder {
TextView textName;
TextView textAmount;
TextView textPrice;
}
public List<myDataClass> parkingList;
private CustomAdapter(List<myDataClass> apps, Context context) {
this.parkingList = apps;
this.context = context;
arrayList = new ArrayList<myDataClass>();
arrayList.addAll(parkingList);
}
#Override
public int getCount() {
return parkingList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, final ViewGroup parent)
{
View rowView = convertView;
ViewHolder viewHolder = null;
if (rowView == null) {
LayoutInflater inflater = getLayoutInflater();
rowView = inflater.inflate(R.layout.list_boughts, parent, false);
viewHolder = new ViewHolder();
viewHolder.textName = rowView.findViewById(R.id.Name);
viewHolder.textAmount = rowView.findViewById(R.id.sdadprice);
viewHolder.textPrice = rowView.findViewById(R.id.dfsdfad);
rowView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
// here setting up names and images
viewHolder.textName.setText(parkingList.get(position).getProdaname() + "");
viewHolder.textAmount.setText(parkingList.get(position).getAmount());
viewHolder.textPrice.setText(parkingList.get(position).getPrice());
System.out.println(parkingList.get(position).getPrice());
mListview.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
// delete
mDatabaseHelper.delete(parkingList.get(position).getProdaname());
System.out.println(parkingList.get(position).getProdaname());
listData.remove(index);
custom.notifyDataSetChanged();
populateListView();
// false : close the menu; true : not close the menu
return false;
}
});
return rowView;
}
}
Create a Offline database in scoped storage but this database will be deleted when user uninstall the app.
File mainfolder = getDir("datafolder", Context.MODE_PRIVATE);
Bitmap bitmap = BitmapFactory.decode(currentphotopath);
String name = new SimpleDateFormate("dd_mm_yyyy_hhss") + ".jpg"; // this or generate new file name each time user uploads.
File file = new File(mainfolder, name);
FileOutputStreme fout = new FIleOutputStreme(file);
bitmap.compress(jpg, 100, fout);
fout.close();
//listing all the files in mainfolder and set to gridview
File[] files = mainfolder.listFiles();
customView cview = new customView(this, files);
gridview.setAdapter(cview);
//adapter customview class
public class customview extends ArrayAdapter{
private Files[] files;
.
.`
.
public customview (Activity activity, Files[] fls){
files = fls;
}
#Override
public View getView(int position, View convertView, final ViewGroup parent){
Bitmap bitmap = BitmapFactory.decode(files[position].getAbsolutePath());
imageview.setImageBitmap(bitmap);
}
}
I have a relative layout which contains a viewpager to enable to me swipe images fetched from my web service.The fetched images are then stored in a ArrayList which contains a HashMap. I've logged the fetching part of from web service and the log indicates that I am indeed fetching different images. However, whenever I'm swiping from image to image, the viewpager displays the same image which is always the last image saved. I've logged the ArrayList of images in the Pager Adapter and it seems that I am getting the correct arraylist size but I'm getting the same bitmap in all sizes.
This is my PagerAdapter class:
public class ImageAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;
private Context context;
private ArrayList<HashMap<String, Object>> images;
public ImageAdapter(Context context, ArrayList<HashMap<String, Object>> images) {
this.context = context;
this.images = images;
layoutInflater = LayoutInflater.from(context);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.view_pager_image_video, null);
RelativeLayout rlAttach = (RelativeLayout) view.findViewById(R.id.rl_attach);
ImageView imgAttach = (ImageView) view.findViewById(R.id.img_attach);
VideoView vvAttach = (VideoView) view.findViewById(R.id.vv_attach);
LinearLayout llOverlay = (LinearLayout) view.findViewById(R.id.ll_video_overlay);
ProgressBar pBar = (ProgressBar) view.findViewById(R.id.pBar);
LinearLayout llUnsupportFile = (LinearLayout) view.findViewById(R.id.ll_unsupport_file);
Log.d(TAG, "image: " + images.size() + " " + images);
Bitmap image = (Bitmap) images.get(position).get("image");
image = CommonUtilities.checkBitmapRotation(bmp);
imgAttach.setVisibility(View.VISIBLE);
vvAttach.setVisibility(View.GONE);
llOverlay.setVisibility(View.GONE);
llUnsupportFile.setVisibility(View.GONE);
imgAttach.setImageBitmap(image);
pBar.setVisibility(View.GONE);
setPreviewClick(imgAttach, position, rlAttach);
container.addView(view);
return view;
}
#Override
public int getCount() {
return images.size();
}
#Override
public boolean isViewFromObject(View view, Object obj) {
return view == obj;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
}
}
This is where I set the adapter and set notifidydatasetchange:
if (galleryList.size() > 0) {
llNoGallery.setVisibility(View.GONE);
rlHasGallery.setVisibility(View.VISIBLE);
pbGallery.setVisibility(View.GONE);
vpGallery.setVisibility(View.VISIBLE);
tvPageCount.setVisibility(View.VISIBLE);
mImageAdapter = new ImageAdapter(getActivity(), galleryList);
for (HashMap getList : galleryList) {
Log.d(TAG, "onMe: " + getList.toString());
}
vpGallery.setAdapter(mImageAdapter);
vpGallery.addOnPageChangeListener(viewPagerPageChangeListener);
vpGallery.setOffscreenPageLimit(galleryList.size());
mImageAdapter.notifyDataSetChanged();
tvPageCount.setText("1/" + galleryList.size());
} else {
rlHasGallery.setVisibility(View.GONE);
llNoGallery.setVisibility(View.VISIBLE);
}
This is the function to save the images fetched to the arraylist:
private void saveImagesToArrayList(String photo) {
bmp = null;
if (!photo.isEmpty()) {
bmp = imageLoader.loadImageSync(photo);
// tmp hashmap for single image
HashMap<String, Object> hmImage = new HashMap<String, Object>();
// adding each child node to HashMap key => value
hmImage.put("image", bmp);
galleryList.add(hmImage);
// tmp hashmap for single image
HashMap<String, Object> hmImageInString = new HashMap<String, Object>();
// adding each child node to HashMap key => value
hmImageInString.put("image", photo);
galleryListInString.add(hmImageInString);
}
}
This is my ViewPagerChangeListener which shows the position of the image swipped to :
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
tvPageCount.setText(position + 1 + "/" + (galleryList.size()));
}
#Override
public void onPageScrolled(int pos, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
Here I have the setPreviewClick method to open up the image in full screen via intent. The images show here are correct here which displays different images on swipe.
private void setPreviewClick(View view, int imagePosition, RelativeLayout rlAttach) {
final int mPosition = imagePosition;
rlAttach.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
intentViewActivity(mPosition);
}
});
ImageView mImg = (ImageView) view;
mImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
intentViewActivity(mPosition);
}
});
}
The intentViewActivity method is as follows:
public void intentViewActivity(int position) {
Intent intent = new Intent(getActivity(), ViewImageViewPagerActivity.class);
intent.putExtra("images", galleryListInString);
intent.putExtra("image_position", position);
getActivity().startActivity(intent);
}
The one of the parameter of the intentViewActivity method is the ViewImageViewPagerActivity which is this:
package com.epicamera.vms.i_neighbour.activity;
public class ViewImageViewPagerActivity extends AppCompatActivity {
private String TAG = "ViewImageViewPagerActivity";
Toolbar toolbar;
private View temp_view;
private VideoView vv;
private TextView toolbar_title;
private ViewPager insideViewPager;
private MyViewPagerAdapter myViewPagerAdapter;
ArrayList<HashMap<String, Object>> imageList = new ArrayList<>();
Bitmap bmp = null;
ImageLoader imageLoader = ImageLoader.getInstance(); // Get singleton instance
private String username, companyname, usertype, companylogo, userid, token, userphoto, usergender;
private String android_id;
private String regId;
private Bitmap attachment = null;
private int imagePosition = 0, actualPosition = 0;
private int onPageScrollPosition = 0;
private boolean isVideo = false;
private Handler fileCheckerHandler = new Handler();
private Runnable fileCheckerRunnable = null;
private Uri uri;
// AsyncTask
AsyncTask<Void, Void, Boolean> task;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_image_video_viewpager);
CommonUtilities.toggleRotationAdvance(this);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar_title = (TextView) findViewById(R.id.toolbar_title);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_action_back);
// enable ActionBar app icon to behave as action to toggle nav drawer
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
//remove the tittle
getSupportActionBar().setDisplayShowTitleEnabled(false);
SessionManager session = new SessionManager(this.getApplicationContext());
// get user data from session
HashMap<String, String> user = session.getUserDetails();
// session id
username = user.get(SessionManager.KEY_USERNAME);
// user id
companyname = user.get(SessionManager.KEY_COMPANYNAME);
// company id
usertype = user.get(SessionManager.KEY_USERTYPE);
// company id
companylogo = user.get(SessionManager.KEY_COMPANYLOGO);
// user id
userid = user.get(SessionManager.KEY_USERID);
// session token
token = user.get(SessionManager.KEY_TOKEN);
// session user photo
userphoto = user.get(SessionManager.KEY_USERPHOTO);
usergender = user.get(SessionManager.KEY_USERGENDER);
android_id = Settings.Secure.getString(getContentResolver(),
Settings.Secure.ANDROID_ID);
insideViewPager = (ViewPager) findViewById(R.id.inside_view_pager);
imageList = (ArrayList<HashMap<String,Object>>) getIntent().getExtras().getSerializable("images");
imagePosition = getIntent().getExtras().getInt("image_position");
actualPosition = imagePosition;
myViewPagerAdapter = new MyViewPagerAdapter(ViewImageViewPagerActivity.this, imageList);
insideViewPager.setAdapter(myViewPagerAdapter);
insideViewPager.addOnPageChangeListener(viewPagerPageChangeListener);
insideViewPager.setOffscreenPageLimit(imageList.size());
insideViewPager.setCurrentItem(actualPosition, false);
myViewPagerAdapter.notifyDataSetChanged();
toolbar_title.setText(actualPosition + 1 + " / " + (imageList.size()));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// return super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.view_image_menu, menu);
return true;
}
/* Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d(TAG, "id: " + item.getItemId());
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
case R.id.action_savetogallery:
String[] count = toolbar_title.getText().toString().split("/");
int value = Integer.parseInt(count[0].trim()) - 1;
HashMap<String, String> child = new HashMap<>();
child.put("image", (String) imageList.get(value).get("image"));
saveToGallery(child, "File");
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
public void saveToGallery(HashMap<String, String> item, final String type) {
//take the current position
final String select_document_link = item.get("image");
final String select_document_name = item.get("image");
final String selected_document = select_document_name.substring(select_document_name.lastIndexOf('/') + 1, select_document_name.length());
final String document_download_path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM + "/i-Neighbour").getPath() + File.separator + selected_document;
final File file = new File(document_download_path);
Log.d(TAG, "path: " + document_download_path + " " + select_document_link);
// Check is the file is exist
// if (file.exists()) {
// //Open the file if exist
// openFile(file);
// } else {
//Download and open the file, if does not exist
try {
Toast.makeText(ViewImageViewPagerActivity.this, "Downloading...", Toast.LENGTH_SHORT).show();
// final ProgressDialog progDailog = ProgressDialog.show(this,
// this.getResources().getString(R.string.txt_title_downloading),
// this.getResources().getString(R.string.txt_document_downloading), true);
new Thread() {
public void run() {
try {
//Download the document
final DownloadManager downloadManager;
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM + "/i-Neighbour").mkdirs();
downloadManager = (DownloadManager) ViewImageViewPagerActivity.this.getSystemService(Context.DOWNLOAD_SERVICE);
// have to replace space to %20
String url = select_document_link.replace(" ", "%20");
Uri uri = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(uri)
.setTitle(selected_document)
.setDestinationInExternalPublicDir(Environment.DIRECTORY_DCIM + "/i-Neighbour",
selected_document)
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
downloadManager.enqueue(request);
//ADDED LOOP HERE UNTIL FILE DOWNLOAD IS COMPLETE
fileCheckerRunnable = new Runnable() {
public void run() {
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterByStatus(DownloadManager.STATUS_FAILED | DownloadManager.STATUS_PAUSED | DownloadManager.STATUS_SUCCESSFUL | DownloadManager.STATUS_RUNNING | DownloadManager.STATUS_PENDING);
Cursor cursor = downloadManager.query(query);
if (cursor.moveToFirst()) {
int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
switch (status) {
case DownloadManager.STATUS_PAUSED:
//download is waiting to retry or resume
fileCheckerHandler.postDelayed(this, 1000);
break;
case DownloadManager.STATUS_PENDING:
//download is waiting to start
fileCheckerHandler.postDelayed(this, 1000);
break;
case DownloadManager.STATUS_RUNNING:
//download is currently running
fileCheckerHandler.postDelayed(this, 1000);
break;
case DownloadManager.STATUS_SUCCESSFUL:
//download has successfully completed
//Open the document
// openFile(file);
Toast.makeText(ViewImageViewPagerActivity.this, type + " saved to Gallery->i-
Neighbour", Toast.LENGTH_SHORT).show();
// progDailog.dismiss();
//STOP REPEATING TASK
fileCheckerHandler.removeCallbacks(fileCheckerRunnable);
break;
case DownloadManager.STATUS_FAILED:
//download has failed (and will not be retried)
// progDailog.dismiss();
//STOP REPEATING TASK
fileCheckerHandler.removeCallbacks(fileCheckerRunnable);
break;
}
}
}
};
fileCheckerHandler.postDelayed(fileCheckerRunnable, 1000);
} catch (Exception e) {
Log.d(TAG, "Error: " + e);
}
}
}.start();
} catch (Exception e) {
Log.e("ERROR", "Error -> " + e.getMessage());
}
}
// outside viewpager change listener
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
toolbar_title.setText(position + 1 + " / " + (imageList.size()));
onPageScrollPosition = position;
Log.d(TAG, "onpagescrollposition: " + onPageScrollPosition);
}
#Override
public void onPageScrolled(int pos, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
/**
* View pager adapter
*/
public class MyViewPagerAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;
private Context context;
private ArrayList<HashMap<String, Object>> images;
public MyViewPagerAdapter(Context context, ArrayList<HashMap<String, Object>> images) {
this.context = context;
this.images = images;
layoutInflater = LayoutInflater.from(context);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.view_pager_image_video2, null);
final VideoView vvFullScreen = (VideoView) view.findViewById(R.id.vv_full_screen);
final TouchImageView imgFullScreen = (TouchImageView) view.findViewById(R.id.img_full_screen);
final ImageView imgVideoBg = (ImageView) view.findViewById(R.id.img_video_bg);
final ProgressBar pBar = (ProgressBar) view.findViewById(R.id.pBar);
final LinearLayout llVideoPlay = (LinearLayout) view.findViewById(R.id.ll_video_play);
view.setTag("pos" + position);
//Bitmap image = (Bitmap) images.get(position).get("image");
String image_url = (String) images.get(position).get("image");
imgFullScreen.setVisibility(View.VISIBLE);
vvFullScreen.setVisibility(View.GONE);
llVideoPlay.setVisibility(View.GONE);
Glide.with(context).load(image_url)
.thumbnail(0.5f)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(imgFullScreen);
container.addView(view);
return view;
}
#Override
public int getCount() {
return images.size();
}
#Override
public boolean isViewFromObject(View view, Object obj) {
return view == obj;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
}
#Override
public int getItemPosition(Object object) {
return super.getItemPosition(object);
}
}
}
I want to create a cache that stores present listview populated from the server which means even if users are not online they can have access to the listview data been loaded before going offline. These are my codes that contains the swipelistlayout and the main class Tab4
public class Tab4 extends android.support.v4.app.Fragment implements SwipeRefreshLayout.OnRefreshListener {
private int index;
ImageSwitcher switcher;
android.os.Handler Handler = new android.os.Handler();
private SwipeRefreshLayout swipeRefreshLayout;
private SwipeListAdapter adapter;
private List<Movie> movieList;
private ListView listView;
private String URL_TOP_250 = "http://172.126.43.152/locator/test/refractor2.php?offset=";
private int offSet = 0;
private static final String TAG = Tab1.class.getSimpleName();
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View vi = inflater.inflate(R.layout.tab_4,container,false);
listView = (ListView) vi.findViewById(R.id.list4);
listView.setBackgroundColor(Color.WHITE);
// Adding request to request queue
//Editted AppController.getInstance().addToRequestQueue(movieReq);
swipeRefreshLayout = (SwipeRefreshLayout) vi.findViewById(R.id.swipe_refresh_layout);
movieList = new ArrayList<>();
adapter = new SwipeListAdapter(getActivity(), movieList);
listView.setAdapter(adapter);
//getView().setOnClickListener();
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
fetchMovies();
}
}
);
return vi;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Intent intent = new Intent();
intent.setClass(getActivity(), Newbies.class);
//String text = String.valueOf(movieList.get(position));
String text = movieList.get(position).getSlug();
//Toast.makeText(getActivity().getApplicationContext(), text, Toast.LENGTH_LONG).show();
Intent i = new Intent(getActivity(), Newbies.class);
i.putExtra("TEXT", text);
startActivity(i);
}
});
}
#Override
public void onRefresh() {
fetchMovies();
}
private void fetchMovies() {
// showing refresh animation before making http call
swipeRefreshLayout.setRefreshing(true);
// appending offset to url
String url = URL_TOP_250 + offSet;
// Volley's json array request object
JsonArrayRequest req = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
if (response.length() > 0) {
// looping through json and adding to movies list
for (int i = 0; i < response.length(); i++) {
try {
JSONObject movieObj = response.getJSONObject(i);
// Movie m = new Movie();
int rank = movieObj.getInt("rank");
String title = movieObj.getString("postTitle");
String author = movieObj.getString("postAuthor");
String slug = movieObj.getString("postSlug");
String categories = "technologies";
String thumbnailUrl = movieObj.getString("postPic");
String year = movieObj.getString("postDate");
Movie m = new Movie(rank, title, author, slug, categories, thumbnailUrl, year);
movieList.add(0, m);
// updating offset value to highest value
if (rank >= offSet)
offSet = rank;
} catch (JSONException e) {
Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
}
adapter.notifyDataSetChanged();
}
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Server Error: " + error.getMessage());
Toast.makeText(getActivity().getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
}
And the SwipeListAdapter class is below...
public class SwipeListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Movie> movieList;
private String[] bgColors;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public SwipeListAdapter(Activity tab1, List<Movie> movieList) {
this.activity = tab1;
this.movieList = movieList;
bgColors = activity.getApplicationContext().getResources().getStringArray(R.array.movie_serial_bg);
}
#Override
public int getCount() {
return movieList.size();
}
#Override
public Object getItem(int location) {
return movieList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_row, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbNail = (NetworkImageView) convertView
.findViewById(R.id.thumbnail);
TextView title = (TextView) convertView.findViewById(R.id.title);
TextView author = (TextView) convertView.findViewById(R.id.author);
//String slug;
TextView category = (TextView) convertView.findViewById(R.id.category);
TextView year = (TextView) convertView.findViewById(R.id.releaseYear);
// getting movie data for the row
Movie m = movieList.get(position);
// thumbnail image
thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);
// title
title.setText(m.getTitle());
author.setText(m.getAuthor());
// slug.setText(m.getAuthor());
category.setText(m.getCategories());
// release year
year.setText(String.valueOf(m.getYear()));
return convertView;
}
}
Any help will be appreciated. Thanks.
i am using eclipse.
Basically what i am trying to implement is that , that i have a gridView which is fetching images from mysql database dynamically using JSON.
Now , instead of gridview i want to show them as coverflow view.
I have searched through the internet , but was not able to find any library or example for dynamic images , i only found for static images stored in the app itself and not on external database.
My code are as follows:-
MainActivity.java:-
public class MainActivity extends Activity implements OnClickListener {
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
// Movies json url
private static final String url = "http://eventassociate.com/wedding/photomania";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private PullToRefreshGridView mPullRefreshGridView;
private GridView gridView;
private CustomListAdapter adapter;
ImageButton blackcapture;
private static int RESULT_LOAD_IMAGE = 1;
String picturePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.gallary_activity_main);
overridePendingTransition(R.anim.push_down_in, R.anim.push_down_out);
mPullRefreshGridView = (PullToRefreshGridView) findViewById(R.id.list);
gridView = mPullRefreshGridView.getRefreshableView();
mPullRefreshGridView.setOnRefreshListener(new OnRefreshListener2<GridView>() {
#Override
public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {
adapter.notifyDataSetChanged();
gridView.setAdapter(adapter);
gridView.invalidateViews();
mPullRefreshGridView.onRefreshComplete();
}
adapter = new CustomListAdapter(this, movieList);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Movie m5 = movieList.get(position);
Intent i = new Intent(getApplicationContext(),
FullImageActivity.class);
i.putExtra("movieobject", m5);
startActivity(i);
}
});
Adapter Class:-
public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
List<Movie> movieItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapter(Activity activity, List<Movie> movieItems) {
this.activity = activity;
this.movieItems = movieItems;
}
#Override
public int getCount() {
return movieItems.size();
}
#Override
public Object getItem(int location) {
return movieItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.gallary_list_row, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbNail = (NetworkImageView) convertView
.findViewById(R.id.thumbnail);
// ...............................................
TextView title = (TextView) convertView.findViewById(R.id.title);
// getting movie data for the row
Movie m = movieItems.get(position);
// thumbnail image
thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);
// title
title.setText(m.getTitle());
return convertView;
}
Movie.java:-
public class Movie implements Parcelable{
private String title,thumbnailUrl;
public Movie() {
// TODO Auto-generated constructor stub
}
public Movie(String name, String thumbnailUrl
) {
this.title = name;
this.thumbnailUrl = thumbnailUrl;
}
public String getTitle() {
return title;
}
public void setTitle(String name) {
this.title = name;
}
public String getThumbnailUrl() {
return thumbnailUrl;
}
public void setThumbnailUrl(String thumbnailUrl) {
this.thumbnailUrl = "http://eventassociate.com/wedding/"+thumbnailUrl;
}
// Parcelling part
public Movie(Parcel in){
String[] data = new String[2];
in.readStringArray(data);
this.title = data[0];
this.thumbnailUrl = data[1];
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeStringArray(new String[] {this.title,
this.thumbnailUrl,
});
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public Movie createFromParcel(Parcel in) {
return new Movie(in);
}
public Movie[] newArray(int size) {
return new Movie[size];
}
};
}
I successfully implemented this as GridView , but i am facing trouble in implementing this as coverflow design or something like that.
I searched on the net and i find this code , but only for static images:-
public class SimpleExample extends Activity {
// =============================================================================
// Child views
// =============================================================================
private FancyCoverFlow fancyCoverFlow;
// =============================================================================
// Supertype overrides
// =============================================================================
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.fancyCoverFlow = (FancyCoverFlow) this.findViewById(R.id.fancyCoverFlow);
this.fancyCoverFlow.setAdapter(new FancyCoverFlowSampleAdapter());
this.fancyCoverFlow.setUnselectedAlpha(1.0f);
this.fancyCoverFlow.setUnselectedSaturation(0.0f);
this.fancyCoverFlow.setUnselectedScale(0.5f);
this.fancyCoverFlow.setSpacing(50);
this.fancyCoverFlow.setMaxRotation(0);
this.fancyCoverFlow.setScaleDownGravity(0.2f);
this.fancyCoverFlow.setActionDistance(FancyCoverFlow.ACTION_DISTANCE_AUTO);
}
// =============================================================================
// Private classes
// =============================================================================
}
Adapter.java:-
public class FancyCoverFlowSampleAdapter extends FancyCoverFlowAdapter {
// =============================================================================
// Private members
// =============================================================================
private int[] images = {R.drawable.image1, R.drawable.image2, R.drawable.image3, R.drawable.image4, R.drawable.image5, R.drawable.image6,};
// =============================================================================
// Supertype overrides
// =============================================================================
#Override
public int getCount() {
return images.length;
}
#Override
public Integer getItem(int i) {
return images[i];
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getCoverFlowItem(int i, View reuseableView, ViewGroup viewGroup) {
ImageView imageView = null;
if (reuseableView != null) {
imageView = (ImageView) reuseableView;
} else {
imageView = new ImageView(viewGroup.getContext());
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setLayoutParams(new FancyCoverFlow.LayoutParams(300, 400));
}
imageView.setImageResource(this.getItem(i));
return imageView;
}
}
Can someone help me , in solving my problem.
Thanks.
My final code with coverflow:-
MainActivity:-
public class MainActivity extends Activity implements OnClickListener {
// Log tag
private static final String TAG = album.MainActivity.class.getSimpleName();
// Movies json url
private static final String url = "http://eventassociate.com/wedding/androidadminimages";
private ProgressDialog pDialog;
private List<Moviealbum> movieList = new ArrayList<Moviealbum>();
private FancyCoverFlow fancyCoverFlow;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.album_activity_main);
overridePendingTransition(R.anim.push_down_in, R.anim.push_down_out);
this.fancyCoverFlow = (FancyCoverFlow) this.findViewById(R.id.list);
adapter = new CustomListAdapter(this, movieList);
this.fancyCoverFlow.setAdapter(new CustomListAdapter(this, movieList));
this.fancyCoverFlow.setUnselectedAlpha(1.0f);
this.fancyCoverFlow.setUnselectedSaturation(0.0f);
this.fancyCoverFlow.setUnselectedScale(0.5f);
this.fancyCoverFlow.setSpacing(50);
this.fancyCoverFlow.setMaxRotation(0);
this.fancyCoverFlow.setScaleDownGravity(0.2f);
this.fancyCoverFlow.setActionDistance(FancyCoverFlow.ACTION_DISTANCE_AUTO);
fancyCoverFlow.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Moviealbum m5 = movieList.get(position);
Intent i = new Intent(getApplicationContext(),album.
FullImageActivity.class);
i.putExtra("movieobject", m5);
startActivity(i);
}
});
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// changing action bar color
getActionBar().setBackgroundDrawable(
new ColorDrawable(Color.parseColor("#1b1b1b")));
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Moviealbum movie = new Moviealbum();
movie.setTitle(obj.getString("no"));
movie.setThumbnailUrl(obj.getString("alinks"));
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue...................................
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
AdapterClass :-
public class CustomListAdapter extends FancyCoverFlowAdapter {
private Activity activity;
private LayoutInflater inflater;
List<Moviealbum> movieItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapter(Activity activity, List<Moviealbum> movieItems) {
this.activity = activity;
this.movieItems = movieItems;
}
#Override
public int getCount() {
return movieItems.size();
}
#Override
public Object getItem(int location) {
return movieItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getCoverFlowItem(int position, View reuseableView, ViewGroup viewGroup) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (reuseableView == null)
reuseableView = inflater.inflate(R.layout.gallary_list_row, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbNail = (NetworkImageView) reuseableView
.findViewById(R.id.thumbnail);
// ...............................................
TextView title = (TextView) reuseableView.findViewById(R.id.title);
// getting movie data for the row
Moviealbum m = movieItems.get(position);
// thumbnail image
thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);
// title
title.setText(m.getTitle());
return reuseableView;
}
The app runs fine , but after loading blank screen is shown with no images.
Logcat:-
Your issue isn't with the CoverFlow code, but rather where you're doing your network operation. On app load, begin your network request for your JSON payload, show a spinner to show the app is loading, and populate your Adapter once your images are loaded. I'm assuming you have network code already given your GridView implementation? Let me know if I've missed something. I hope that helps!
EDIT:
Once you've added images to your Adapter make sure you call notifyDataSetChanged() to tell your adapter to reload its views.
EDIT 2:
Look at this line here:
this.fancyCoverFlow.setAdapter(new CustomListAdapter(this, movieList));
You're passing a new CustomListAdapter rather than passing in your adapter variable. Try fixing that and let me know if it works.
What i am doing::
I am opening a camera onclick of item from actionbar menu
I am capturing the image and setting it in a listview
What is happening::
Say i have captured 10 images and set it in listview
next time i run my code, i am able to find the images i took last
time, and it dosen't start from groundup
What i am trying to do:
say i captured 10 images and set in listview
next time i start the app and start capturing the image it should add
freshly captured images to listview and not display the old images
i am not telling i have to delete these images but i the app i want
to show newly captured images everytime
MainActivity.java
public class MainActivity extends ListActivity {
private static final int CAMERA_CAPTURE = 20;
ArrayList<String> listOfImages;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DisplayCapturedImagesFromCamera();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_camera) {
startCameraCapture();
return true;
}
return super.onOptionsItemSelected(item);
}
private void startCameraCapture() {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = CreateImageFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(photoFile != null)
{
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(cameraIntent, CAMERA_CAPTURE);
}
}
}
private File CreateImageFile() throws IOException
{
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "Image_" + timeStamp + "_";
File storageDirectory = getExternalFilesDir("");
File image = File.createTempFile(imageFileName, ".jpg",storageDirectory);
return image;
}
#Override
public void onActivityResult(final int requestCode, int resultCode, Intent data) {
switch(requestCode)
{
case CAMERA_CAPTURE:
if(resultCode == RESULT_OK)
{
DisplayCapturedImagesFromCamera();
}
break;
}
}
private void DisplayCapturedImagesFromCamera() {
// TODO Auto-generated method stub
File myPath = getExternalFilesDir(null);
listOfImages = new ArrayList<String>();
try
{
for(File f: myPath.listFiles()) {
listOfImages.add(f.getAbsolutePath());
}
AdptAddjobsGallery adapter = new AdptAddjobsGallery(MainActivity.this,listOfImages);
setListAdapter(adapter);
}
catch(Exception ex)
{
Log.w("Error", ex.getMessage());
}
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
// custom dialog
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.cust_dialog);
dialog.setTitle("Image ");
Bitmap bitmap = BitmapFactory.decodeFile(listOfImages.get(position));
// set the custom dialog components - text, image and button
ImageView image = (ImageView) dialog.findViewById(R.id.image);
image.setImageBitmap(bitmap);
Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
dialog.dismiss();
}
});
dialog.show();
}
}
AdptAddjobsGallery.java
public class AdptAddjobsGallery extends ArrayAdapter<String> {
private final Activity context;
private final ArrayList<String> listOfImages;
public AdptAddjobsGallery(Activity context, ArrayList<String> listOfImages) {
super(context, R.layout.adpt_addjobs_gallery, listOfImages);
// TODO Auto-generated constructor stub
this.context=context;
this.listOfImages = listOfImages;
}
public View getView(int position,View view,ViewGroup parent) {
ViewHolder holder;
if(view == null)
{
LayoutInflater inflater=context.getLayoutInflater();
view =inflater.inflate(R.layout.adpt_addjobs_gallery, null,true);
holder = new ViewHolder();
holder.imageView = (ImageView) view.findViewById(R.id.selfie);
holder.txtTitle = (TextView) view.findViewById(R.id.fileName);
view.setTag(holder);
}
else
{
holder = (ViewHolder) view.getTag();
}
Bitmap bitmap = BitmapFactory.decodeFile(listOfImages.get(position));
File f = new File(listOfImages.get(position));
holder.txtTitle.setText(f.getName());
holder.imageView.setImageBitmap(bitmap);
return view;
};
}
class ViewHolder {
TextView txtTitle;
ImageView imageView;
}
try this, using file.lastmodified() method.
private ArrayList<String> getRecentImages(long from, long to,
ArrayList<String> list) {
ArrayList<String> sortedList = new ArrayList<String>();
for (int i = 0; i < list.size(); i++) {
File file = new File(list.get(i));
long modified = file.lastModified();
if (modified > from && modified <= to) {
sortedList.add(list.get(i));
}
}
return sortedList;
}