I've been working on making a video gallery for myself and got stuck here. Followed this link for some references but still getting some problems:
For making thumbnails for the videos
Here is my code :
public class AddFragment extends Fragment {
private ImageButton imageButton;
private GridView gridView;
private File files;
ArrayList<File> list;
public AddFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_add, container, false);
imageButton = (ImageButton) view.findViewById(R.id.gotoButton);
gridView = (GridView) view.findViewById(R.id.grid_view);
gridView.setAdapter(new ImageAdapter(getContext()));
list = videoReader(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES));
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
//for making the button visible as ssonas the item gets selected
imageButton.setVisibility(view.VISIBLE);
}
});
return view;
}
ArrayList<File> videoReader(File root) {
ArrayList<File> arrayList = new ArrayList<>();
File[] file = root.listFiles();
for(int i=0;i<file.length;i++){
if(file[i].isDirectory()){
}else{
if(file[i].getName().endsWith(".mp4")){
arrayList.add(file[i]);
}
}
}
return arrayList;
}
public class ImageAdapter extends BaseAdapter{
private Bitmap bitmap;
private final Context context;
private ImageAdapter(Context c){
context = c;
}
//for the video numbers
#Override
public int getCount() {
return list.size();
}
//for getting the video items position vise
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
ImageView picturesView;
if (convertView == null) {
picturesView = new ImageView(context);
if(list.get(position).contains(".jpg"))
{
bitmap = BitmapFactory.decodeFile(list.get(position)); //Creation of Thumbnail of image
}
else if(list.get(position).contains(".mp4"))
{
bitmap = ThumbnailUtils.createVideoThumbnail(list.get(position), 0); //Creation of Thumbnail of video
}
picturesView.setScaleType(ImageView.ScaleType.FIT_CENTER);
picturesView.setPadding(8, 8, 8, 8);
picturesView.setLayoutParams(new GridView.LayoutParams(100, 100));
}
else
{
picturesView = (ImageView)convertView;
}
return picturesView;
}
} }
The problems I'm getting are in my ImageAdapter class in getView method
These are :
1. In the if(list.get(position).contains(".jpg")) //cannot resolve contains
2. In bitmap = BitmapFactory.decodeFile(list.get(position)); //saying the decodeFile(java.lang.string) from Bitmapfacotory cannot be applied to (java.file.io)
P.S. for the second option I tried doing that after getting reference from this link but failed:
Java contradicting behavior resolved
Try this.
if(list.get(position).contains(".jpg"))
{
bitmap = BitmapFactory.decodeFile(list.get(position).toString());
}
list.get(position) is File object and you need to pass String object so just make it String by writing .toString().
contains expect to see the same object type as the list items. if you want to check if the file is an image read this: Android: How to check if file is image?
Decode file expects to get a file url and not a file object. see here how to use it: Bitmapfactory example
Related
I'm setting up an image adapter in my fragments. I recently learn the usefulness of Fragments and Therefore I am trying to switch from the traditional activities to a central activity with multiple fragments. But I cant get to display my images' infinite cycler view.
I have tried reading answers from previous questions here on Stack overflow (ImageAdapter cannot be applied to fragment class and ImageAdapter cannot be applied to a Fragment Class) but I didnt really understand anything perhaps because I am a beginner in android studio with no educational background in coding. I have also tried youtube and everywhere.
I havent found tutorials to do this, I understand that fragments is relatively new in android studio
This is the fragment I am trying to switch to
public TrendingFragment() {
// Required empty public constructor
}
private static final String TAG = "Trending";
HorizontalInfiniteCycleViewPager viewPager;
List<TrendingHolder> TrendingList = new ArrayList<>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragme
View view = inflater.inflate(R.layout.fragment_trending, container, false);
initData();
viewPager = view.findViewById(R.id.view_pager);
viewPager.setAdapter(new TrendingAdapter(getActivity()));
return view;
}
private void initData() {
//Adding the Images on board
TrendingList.add(new TrendingHolder(R.drawable.ad_test));
TrendingList.add(new TrendingHolder(R.drawable.burger_test));
TrendingList.add(new TrendingHolder(R.drawable.italian_test));
TrendingList.add(new TrendingHolder(R.drawable.pizza_test));
}
}
This is my adapter class
public class TrendingAdapter extends PagerAdapter {
Context context;
List<TrendingHolder> TrendingList;
private static final String TAG = "TrendingAdapter";
public TrendingAdapter(Context context, List<TrendingHolder> trendingList) {
this.context = context;
this.TrendingList = trendingList;
}
#Override
public int getCount() {
return TrendingList.size();
}
#Override
public boolean isViewFromObject(View view, #NonNull Object o){
return view.equals(o);
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((View)object);
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
//Inflate View
View view = LayoutInflater.from(context).inflate(R.layout.card_item, container, false);
//View
ImageView trending_image = (ImageView)view.findViewById(R.id.trending_holder);
//Set Data
trending_image.setImageResource(TrendingList.get(position).getImage());
//set On Event Click
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//shop activity comes here
Log.d(TAG, "onClick: added to Cart");
}
});
container.addView(view);
return view;
}
}
This is my model for the images
public class TrendingHolder {
private int image;
public TrendingHolder(){
}
public TrendingHolder(int image) {
this.image = image;
}
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
}
I am getting this error TrendingAdapter( )
in TrendingAdapter cannot be applied
to
(androidx.fragment.app.FragmentActivity) in my Trending Fragment
It seems like missing constructor parameter. The constructor of TrendingAdapter accepts 2 parameters public TrendingAdapter(Context context, List<TrendingHolder> trendingList). But you pass 1 parameter viewPager.setAdapter(new TrendingAdapter(getActivity()));.
I'm not exactly sure what I'm missing, but I've been trying to get the most popular movie posters to display in a gridview from themoviedb API utilizing the Picasso library. Anyone know what I'm doing wrong?
Here's my ImageAdapter:
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return 20;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
Picasso.with(mContext).load("https://api.themoviedb.org/3/movie/popular?api_key={APIKEY_HERE}&poster_path&images").into(imageView);
} else {
imageView = (ImageView) convertView;
}
return imageView;
}
}
Above mentioned API will give popular movie list this..
results: [
{
poster_path: "/inVq3FRqcYIRl2la8iZikYYxFNR.jpg",
adult: false,
overview: "life.",
release_date: "2016-02-09",
backdrop_path: "/nbIrDhOtUpdD9HKDBRy02a8VhpV.jpg",
popularity: 91.92864,
vote_count: 3497,
video: false,
vote_average: 7.2
}
]
Extract poster_path of which movie image you want to display
Use the below URL to display image http://image.tmdb.org/t/p/w500/inVq3FRqcYIRl2la8iZikYYxFNR.jpg
You can find the document here http://docs.themoviedb.apiary.io/#reference/configuration/configuration
you have to check that url in picasso it returns the whole data not the image url, try to add the value of poster_path to the right url
I was following a NewBoston Tutorial (https://www.youtube.com/watch?v=nOdSARCVYic&list=PL6gx4Cwl9DGBsvRxJJOzG4r4k_zLKrnxl&index=48)
He showed how to put an image into a list but he never showed how to assign a different image to every piece of text.
Here is my MainActivity.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] Jobsites = {"River Park Place", "Mayfair", "Jameson House"};
ListAdapter jobsiteAdapter = new CustomAdapter(this, Jobsites);
ListView jobsiteListView = (ListView) findViewById(R.id.jobsiteListView);
jobsiteListView.setAdapter(jobsiteAdapter);
jobsiteListView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String jobsite = String.valueOf(parent.getItemAtPosition(position));
//Toast.makeText(MainActivity.this, jobsite, Toast.LENGTH_LONG).show();
if (jobsite == "River Park Place"){
//Perform segue to the proper view where employess can sign in
//******************************************
System.out.println("*****************");
System.out.println("Attempting to segue");
System.out.println("*****************");
//******************************************
}else{
System.out.println("*****************");
System.out.println("These jobsites aren't avaliable yet!");
System.out.println("*****************");
Toast.makeText(MainActivity.this, "**These Sites aren't avaliable yet!**", Toast.LENGTH_LONG).show();
}
}
}
);
}
}
During the video we made a custom View that handles the images. Here is the code.
class CustomAdapter extends ArrayAdapter<String> {
public CustomAdapter(Context context, String[] jobsites) {
super(context,R.layout.custom_row ,jobsites);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater jobsiteInflater = LayoutInflater.from(getContext());
View customView = jobsiteInflater.inflate(R.layout.custom_row, parent, false);
String singleJobsiteItem = getItem(position);
ImageView josbiteImage = (ImageView) customView.findViewById(R.id.josbiteImage);
josbiteImage.setImageResource(R.drawable.riverparkplace);
return customView;
}
}
I have two other images that I want to add in for the bottom two items of text in the list. Right now it is just loading the SAME picture over and over again for all three rows in the list.
Let me guide you through this step by step. Before we continue, you need to understand that ArrayAdapter of your ListView populates each row with the data you specify to it. In other words, You would like to pass the image to the adapter just like you did with the Jobsites String array.
Define a simple wrapper object that contains your String (Jobsites) and the image you would like to assign to it.
public class SimpleObject {
private String jobSite;
private int imageID; // your R.drawable.image
public SimpleObject(String jobSite, int imageID) {
this.jobSite = jobSite;
this.imageID = imageID;
}
public String getJobSite() {
return jobSite;
}
public int getImageID() {
return imageID;
}
}
Initialise your SimpleObject array to be used by the adapter. In your onCreate() of the main activity, do the following:
ArrayList<SimpleObject> objectList = new ArrayList<>();
objectList.add(new SimpleObject("River Park Place", R.drawable.image1);
objectList.add(new SimpleObject("Mayfair", R.drawable.image2);
// the list goes on....
Now, change your CustomAdapter to hold the SimpleObject instead of String:
class CustomAdapter extends ArrayAdapter<SimpleObject> {
public CustomAdapter(Context context, ArrayList<SimpleObject> objectList) {
super(context,R.layout.custom_row ,objectList);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater jobsiteInflater = LayoutInflater.from(getContext());
View customView = jobsiteInflater.inflate(R.layout.custom_row, parent, false);
// Get the SimpleObject
SimpleObject item = (SimpleObject) getItem(position);
String singleJobsiteItem = item.getJobSite(); // get the String
ImageView josbiteImage = (ImageView) customView.findViewById(R.id.josbiteImage);
josbiteImage.setImageResource(item.getImageID()); // get the image ID and assign it to jobsiteImage :)
return customView;
}
}
Now make sure you initialise the adapter in your main activity with the new SimpleObject list:
ListAdapter jobsiteAdapter = new CustomAdapter(this, objectList);
You need to implement baseadapter because of the images
I have searched multiple websites, android developer sites and after no luck to my issue had to seek the community help. All help and suggestion will be highly appreciated.
ISSUE :
I have in total 12 images that I receive from the server (Parse in here) and I show each of them in a PagerAdapter. If all the values are not null the adapter code works fine, the twist is I allow null values to be stored in server. When I get the whole list back from server, I just want to have those views in adapter which contains not null.
Example : Suppose 5 null paths I get then my adapter shows in total 12 views (7 with images, rest as blank pages).
My Adapter Code:
public class ProfileImageAdapter extends PagerAdapter implements OnTouchListener{
private Context localContext;
private LayoutInflater inflater;
private List<DataModel> parseObjects = new ArrayList<DataModel>();
private List<Integer> res = new ArrayList<Integer>();
// Declare Variables
private ImageView viewPagerDisplayImage;
/**
*
* #param context : The context where to display
* #param parseObjects : The ParseObject to work with
*/
public ProfileImageAdapter(Context context, List<DataModel> parseObjects) {
this.localContext = context;
this.parseObjects = parseObjects;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return parseObjects.size();
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return (view == ((LinearLayout) object) && object != null);
}
/**
* What is the item to show
*/
#Override
public Object instantiateItem(ViewGroup container, int position) {
inflater = (LayoutInflater) localContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.profile_image_item, container, false);
// Locate the Image View in viewpager_item.xml
viewPagerDisplayImage = (ImageView) itemView.findViewById(R.id.view_pager_display_image_view);
// Getting the image
try {
ParseFile imageFile = parseObjects.get(position).getImage();
if (imageFile != null) {
byte[] bitmapImageData = imageFile.getData();
Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapImageData, 0, bitmapImageData.length);
viewPagerDisplayImage.setImageBitmap(bitmap);
viewPagerDisplayImage.setOnTouchListener(this);
// Add viewpager_item.xml to ViewPager
itemView.setTag("VALID");
((ViewPager) container).addView(itemView);
} else {
((ViewPager) container).addView(itemView);
itemView.setTag("INVALID");
destroyItem(container, position, itemView);
}
} catch (ParseException e) {
e.printStackTrace();
}
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
// Remove viewpager_item.xml from ViewPager
//((ViewPager) container).invalidate();
((ViewPager) container).removeView((View) object);
}
}
My PagerActivity
public class PageViewerProfileImages extends Activity {
private ViewPager viewPager;
private ProfileImageAdapter profileImageAdapter;
private UserModel userModel = new UserModel();
// Create the Page View for the Profile Images
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile_pager);
List<DataModel> parseObjects = userModel.getDataModels();
viewPager = (ViewPager) findViewById(R.id.pagerProfile);
profileImageAdapter = new ProfileImageAdapter(this, parseObjects);
// Setting the adapter
viewPager.findViewWithTag("VALID");
viewPager.setAdapter(profileImageAdapter);
}
}
My references:
http://developer.android.com/reference/android/support/v4/view/PagerAdapter.html#instantiateItem(android.view.ViewGroup, int)
ViewPager PagerAdapter not updating the View
Create a condition where you parse your server response.
if(imageUrl!=null){
// write code to add image url in your list, which will you pass in your adapter.
}
After using it, it will pass in adapter only those value in adapter which have some value, then it will work.
You can place this condition in adapter when you pass your image-Url list and assign value in your adapter list.
then before assigning your value please check same condition then assign.
I have a dynamic array of drawables and want to display them in a scrollable list. The thing I am having the most trouble with is the array adapter. I don't get any compile time errors with this code, but the runtime error I get is -
Process: com.example.michael.myandroidappactivity, PID: 12297
java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView
I don't want to use a textview though! Here's the main code-
public class cards extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_old_cards);
ListView list = (ListView)findViewById(R.id.showCardList);
cardPile tmp = cardPile.getInstance();
ArrayList<Integer> discardPile = tmp.getDiscardPile();
ArrayAdapter<Integer> imgAdapt = new ArrayAdapter<Integer>(this,R.layout.listview_layout,discardPile);
list.setAdapter(imgAdapt);
}
}
You have to create a new class that extends the BaseAdapter interface and modify the getView method to return the view you want to show in your ListView. For example:
public class ImageAdapter extends BaseAdapter
{
private Context context;
private ArrayList<Integer> imagesIds;
public ImageAdapter(Context _context, ArrayList<Integer> _imageIds)
{
context = _context;
imageIds = _imageIds;
}
#Override
public int getCount()
{
return imgIds.size();
}
#Override
public Object getItem(int position)
{
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView view;
if( convertView != null ) // recycle call
{
view = (ImageView) convertView;
}
else
{
view = new ImageView(context);
image.setBackgroundResource(imageIds.get(position));
}
return view;
}
}
Then modify your listView adapter as:
list.setAdapter( new ImageAdapter( this, discardPile) );