I'm making a Wallpaper app using RecyclerView, and I want to know how to do random (shuffle), so I'm looking for a way, but I can't find a good way. Please let me know how to solve it. Thank you in advance.
I share the source I am using. I am not a professional developer, but I am a person who makes apps as a hobby, so I still lack a lot. Sorry and thank you.
MainActivity
public class MainActivity extends AppCompatActivity {
FloatingActionButton option_01;
FloatingActionButton option_02;
FloatingActionButton option_03;
FloatingActionButton option_04;
static final int PERMISSIONS_REQUEST = 0x0000001;
//종료팝업 전면광고 추가
private static final String TAG = "ted";
TedAdmobDialog nativeTedAdmobDialog;
private AdView mAdView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MobileAds.initialize(this, getString(R.string.admob_app_id));
mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
checkPermission();
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(this, 2);
RecyclerView recyclerView = findViewById(R.id.rv_images);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(layoutManager);
recyclerView.addItemDecoration(new SpacesItemDecoration());
ImageGalleryAdapter adapter = new ImageGalleryAdapter(this, WallPhoto.getWallPhotos());
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
option_01 = findViewById(R.id.option_01);
option_01.setOnClickListener(v -> {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + getPackageName()));
startActivity(intent);
});
option_02 = findViewById(R.id.option_02);
option_02.setOnClickListener(v -> {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/developer?id=Project+J+Lab"));
startActivity(intent);
});
option_03 = findViewById(R.id.option_03);
option_03.setOnClickListener(v -> {
Intent myintent = new Intent(Intent.ACTION_SEND);
myintent.setType("text/plan");
String shereBoday = "Your Boday Here";
String shereSub = "\"http://play.google.com/store/apps/details?id=" + getPackageName();
myintent.putExtra(Intent.EXTRA_SUBJECT, shereBoday);
myintent.putExtra(Intent.EXTRA_TEXT, shereSub);
startActivity(Intent.createChooser(myintent, "shere Using"));
});
option_04 = findViewById(R.id.option_04);
option_04.setOnClickListener(v -> {
Intent email = new Intent(Intent.ACTION_SEND);
email.setType("plain/text");
String[] address = {"dhsthdwjd1#gmail.com"};
email.putExtra(Intent.EXTRA_EMAIL, address);
email.putExtra(Intent.EXTRA_SUBJECT, getPackageName());
email.putExtra(Intent.EXTRA_TEXT, "text");
startActivity(email);
});
}
#Override
public void onBackPressed() {
//종료팝업 전면광고 추가
nativeTedAdmobDialog = new TedAdmobDialog.Builder(MainActivity.this, TedAdmobDialog.AdType.NATIVE, getString(R.string.banner_ad_unit_id_native))
.setOnBackPressListener(new OnBackPressListener() {
#Override
public void onReviewClick() {
}
#Override
public void onFinish() {
finish();
}
#Override
public void onAdShow() {
log("onAdShow");
nativeTedAdmobDialog.loadNative();
}
})
.create();
nativeTedAdmobDialog.show();
}
//종료팝업 전면광고 추가
private void log(String text) {
Log.d(TAG, text);
}
class ImageGalleryAdapter extends RecyclerView.Adapter<ImageGalleryAdapter.MyViewHolder> {
private WallPhoto[] mWallPhotos;
private Context mContext;
public ImageGalleryAdapter(Context context, WallPhoto[] WallPhotos) {
mContext = context;
mWallPhotos = WallPhotos;
}
#Override
public ImageGalleryAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View photoView = inflater.inflate(R.layout.item_photo, parent, false);
ImageGalleryAdapter.MyViewHolder viewHolder = new ImageGalleryAdapter.MyViewHolder(photoView);
return viewHolder;
}
#Override
public void onBindViewHolder(ImageGalleryAdapter.MyViewHolder holder, int position) {
WallPhoto WallPhoto = mWallPhotos[position];
ImageView imageView = holder.mPhotoImageView;
Picasso.get()
.load(WallPhoto.getUrl())
.resize(200, 320)
.centerCrop()
.into(imageView);
}
#Override
public int getItemCount() {
return (mWallPhotos.length);
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public ImageView mPhotoImageView;
public MyViewHolder(View itemView) {
super(itemView);
mPhotoImageView = itemView.findViewById(R.id.iv_photo);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
WallPhoto WallPhoto = mWallPhotos[position];
Intent intent = new Intent(mContext, DetailActivity.class);
intent.putExtra(DetailActivity.EXTRA_TRAVEL_PHOTO, WallPhoto);
startActivity(intent);
}
}
}
}
private void checkPermission() {
PermissionListener permissionlistener = new PermissionListener() {
#Override
public void onPermissionGranted() {
}
#Override
public void onPermissionDenied(List<String> deniedPermissions) {
}
};
TedPermission.with(this)
.setPermissionListener(permissionlistener)
.setPermissions(
Manifest.permission.SET_WALLPAPER,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_PHONE_STATE,
Manifest.permission.INTERNET,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION)
.check();
}
}
WallPhoto
public class WallPhoto implements Parcelable {
public static final Creator<WallPhoto> CREATOR = new Creator<WallPhoto>() {
#Override
public WallPhoto createFromParcel(Parcel in) {
return new WallPhoto(in);
}
#Override
public WallPhoto[] newArray(int size) {
return new WallPhoto[size];
}
};
private String mUrl;
public WallPhoto(String url) {
mUrl = url;
}
protected WallPhoto(Parcel in) {
mUrl = in.readString();
}
public static WallPhoto[] getWallPhotos() {
return new WallPhoto[]{
new WallPhoto("https://i.pinimg.com/736x/55/42/b4/5542b4fce27fb35f586db30f22aa7a06.jpg"),
new WallPhoto("https://i.pinimg.com/736x/dd/46/07/dd4607dfa77d3954ebd3bc5514d3b160.jpg"),
new WallPhoto("https://i.pinimg.com/736x/b1/a6/d6/b1a6d66f1dc350a6eb07098b031a6a86.jpg"),
new WallPhoto("https://i.pinimg.com/736x/ea/43/16/ea43160566df2e94804dc8494abad75d.jpg"),
new WallPhoto("https://i.pinimg.com/736x/2c/9c/e1/2c9ce1ebebcdd9f94bffa7d3a75ba172.jpg"),
new WallPhoto("https://i.pinimg.com/736x/a7/0a/3d/a70a3d6f310f63df2556233466c0d1a5.jpg"),
new WallPhoto("https://i.pinimg.com/736x/54/b3/20/54b320780750126d3c2c014af78e2642.jpg"),
new WallPhoto("https://i.pinimg.com/736x/3f/cc/ec/3fccec232da73ea7efe334cdfa920085.jpg"),
new WallPhoto("https://i.pinimg.com/736x/3b/c1/9f/3bc19f6a11ce39f1ce534b800001e4e0.jpg"),
new WallPhoto("https://i.pinimg.com/736x/37/a8/6e/37a86eac7b57ad3f768771870aca68ca.jpg"),
};
}
public String getUrl() {
return mUrl;
}
public void setUrl(String url) {
mUrl = url;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(mUrl);
}
}
public void shuffle() {
int mWallPhotoSize = mWallphoto.length();
WallPhoto[] shuffleWallphoto = new WallPhoto[mWallPhotoSize];
boolean[] checkNumber = new boolean[mWallPhotoSize];
for (int i = 0; i < mWallPhotoSize; i++) {
int randomNumber = (int)(Math.random()*mWallPhotoSize);
if (!checkNumber[randomNumber]) {
checkNumber[randomNumber] = true;
shuffleWallphoto[i] = mWallphoto[randomNumber];
} else {
i--;
}
}
mWallphoto = shuffleWallphoto;
}
Related
In my onBindViewholder, I am passing onclickListener to itemview in recycler view. Itemview consists of an array with image and text;
Main Activity
public class MainActivity extends AppCompatActivity {
private AdView mAdView;
private AdView mAdView2;
private static final String TAG = MainActivity.class.getSimpleName();
private RecyclerView firstrecyclerView;
private RecyclerView thirdrecyclerView;
ArrayList<itemModel> items;
String[] iconName = {"ABP Sanjha","Breaking News Punjab","Republic Bharat", "Al Jazeera","DW News","Sky News","Indus Live","CNA","RT News"};
//cannel icons and names
private String[] channelnames={"PTC Punjabi","Chakde TV","T-Series Punjabi", "9X Tashan", "Zee Punjabi" };
private int[] channelimages={R.drawable.ptcpunjabi, R.drawable.chakde, R.drawable.tseries, R.drawable.ninex, R.drawable.zeepunjabi};
private String[] channelID={"UCHJW1_0oPzYZl89wX_jhrgA","UCaT-WGdJLyEDnxZPAKRTbqQ","UCJMSoNjSKRARSIJM3GymRjQ","UCrET5fR2NAUTO2Xp12G0l8A", "UCYF_LfBBxkFBEgaSCNrqW3w"};
private List<channel> channelList=new ArrayList<>();
//youtube player fragment
private YouTubePlayerSupportFragmentX youTubePlayerFragment;
private ArrayList<String> youtubeVideoArrayList;
private YouTubePlayer youTubePlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
generateDummyVideoList();
initializeYoutubePlayer();
setUpRecyclerView();
populateRecyclerView();
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
mAdView2 = findViewById(R.id.adView2);
AdRequest adRequest2 = new AdRequest.Builder().build();
mAdView2.loadAd(adRequest2);
}
/**
* initialize youtube player via Fragment and get instance of YoutubePlayer
*/
private void initializeYoutubePlayer() {
youTubePlayerFragment = (YouTubePlayerSupportFragmentX) getSupportFragmentManager().findFragmentById(R.id.youtube_player_fragment);
if (youTubePlayerFragment == null)
return;
youTubePlayerFragment.initialize(Constants.DEVELOPER_KEY, new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player,
boolean wasRestored) {
if (!wasRestored) {
youTubePlayer = player;
//set the player style default
youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
//cue the 1st video by default
youTubePlayer.cueVideo(youtubeVideoArrayList.get(0));
youTubePlayer.addFullscreenControlFlag(YouTubePlayer.FULLSCREEN_FLAG_ALWAYS_FULLSCREEN_IN_LANDSCAPE);
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider arg0, YouTubeInitializationResult arg1) {
//print or show error if initialization failed
Log.e(TAG, "Youtube Player View initialization failed");
}
});
}
// setup the recycler view here
private void setUpRecyclerView() {
firstrecyclerView = findViewById(R.id.first_recycler_view);
firstrecyclerView.setHasFixedSize(true);
items = new ArrayList<>();
//Horizontal direction recycler view
LinearLayoutManager firstlinearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
firstrecyclerView.setLayoutManager(firstlinearLayoutManager);
firstrecyclerView.setItemAnimator(new DefaultItemAnimator());
for (int i = 0; i < iconName.length; i++) {
itemModel itemModel = new itemModel(iconName[i], youtubeVideoArrayList.get(i));
items.add(itemModel);
}
thirdrecyclerView=findViewById(R.id.third_recycler_view);
thirdrecyclerView.setHasFixedSize(true);
channelList=new ArrayList<>();
LinearLayoutManager thirdlinearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
thirdrecyclerView.setLayoutManager(thirdlinearLayoutManager);
for (int i=0;i < channelnames.length;i++){
channel channel=new channel(channelnames[i],channelimages[i]);
channelList.add(channel);
}
}
//populate the recycler view and implement the click event here
private void populateRecyclerView() {
final CustomAdapter adapterf = new CustomAdapter(this, items);
firstrecyclerView.setAdapter(adapterf);
//set click event
firstrecyclerView.addOnItemTouchListener(new RecyclerViewOnClickListener(this, new RecyclerViewOnClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
if (youTubePlayerFragment != null && youTubePlayer != null) {
//update selected position
adapterf.setSelectedPosition(position);
//load selected video
youTubePlayer.cueVideo(youtubeVideoArrayList.get(position));
}
}
}));
channeladpater channeladpater=new channeladpater(channelList);
thirdrecyclerView.setAdapter(channeladpater);
}
//method to generate dummy array list of videos
private void generateDummyVideoList() {
youtubeVideoArrayList = new ArrayList<>();
//get the video id array from strings.xml
String[] videoIDArray = getResources().getStringArray(R.array.video_id_array);
//add all videos to array list
Collections.addAll(youtubeVideoArrayList, videoIDArray);
}
}
Now I tried to open another activity when itemview is clicked in this way;
channeladapter class;
public class channeladpater extends RecyclerView.Adapter<channeladpater.Channelviewholder> {
private List<channel> channelList;
Context ctx;
public channeladpater(List<channel> channelList) {
this.channelList=channelList;
}
#NonNull
#Override
public Channelviewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view,parent,false);
return new Channelviewholder(view);
}
#Override
public void onBindViewHolder(#NonNull Channelviewholder holder, int position)
{
final channel channel=channelList.get(position);
holder.channelname.setText(channel.getChannelname());
holder.channelimage.setImageResource(channel.getChannelimage());
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClickListener(View v, int position) {
final String[] channelID={"UCHJW1_0oPzYZl89wX_jhrgA","UCaT-WGdJLyEDnxZPAKRTbqQ","UCJMSoNjSKRARSIJM3GymRjQ","UCrET5fR2NAUTO2Xp12G0l8A", "UCYF_LfBBxkFBEgaSCNrqW3w"};
Intent intent=MainActivity2.newIntent(v.getContext(), channelID);
v.getContext().startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return channelList.size();
}
public static class Channelviewholder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView channelname;
public CircleImageView channelimage;
ItemClickListener itemClickListener;
Channelviewholder(#NonNull View itemView) {
super(itemView);
this.channelname=itemView.findViewById(R.id.profile_name);
this.channelimage=itemView.findViewById(R.id.profile_image);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
this.itemClickListener.onItemClickListener(v,getLayoutPosition());
}
public void setItemClickListener(ItemClickListener ic){
this.itemClickListener=ic;
}
}
}
}
the new activity start is basically the list of videos fetched using youtube data api;
MainActivity2
public class MainActivity2 extends AppCompatActivity {
RecyclerView recyclerView;
ArrayList<VideoDetails> videoDetailsoArrayList;
public static String CHANNEL_ID_EXTRA = "channel_id_extra";
public static Intent newIntent(Context context, String[] channelID) {
return new Intent(context, MainActivity2.class).putExtra(CHANNEL_ID_EXTRA, channelID);
}
String API_Key = "AIzaSyA1_spJ4XGWOCekBLCsSAgWderHHl_46m0";
private String[] channelID={"UCHJW1_0oPzYZl89wX_jhrgA","UCaT-WGdJLyEDnxZPAKRTbqQ","UCJMSoNjSKRARSIJM3GymRjQ","UCrET5fR2NAUTO2Xp12G0l8A", "UCYF_LfBBxkFBEgaSCNrqW3w"};
String url="https://www.googleapis.com/youtube/v3/search?part=snippet&channelId="+ Arrays.toString(channelID) +"&maxResults=50&sort=date&key=AIzaSyA1_spJ4XGWOCekBLCsSAgWderHHl_46m0";
adapter adapter;
Context ctx;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
final String channelID = getIntent().getStringExtra(CHANNEL_ID_EXTRA);
recyclerView=findViewById(R.id.listView);
videoDetailsoArrayList= new ArrayList<>();
adapter=new adapter(MainActivity2.this,videoDetailsoArrayList);
displayVideos();
}
private void displayVideos ()
{
RequestQueue requestQueue= Volley.newRequestQueue(this);
StringRequest stringRequest=new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("items");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
if (jsonObject1.has("id")){
JSONObject jsonVideoId=jsonObject1.getJSONObject("id");
if (jsonVideoId.has("kind")){
if(jsonVideoId.getString("kind").equals("youtube#video")) {
JSONObject jsonObjectSnippet = jsonObject1.getJSONObject("snippet");
JSONObject jsonObjectDefault = jsonObjectSnippet.getJSONObject("thumbnails").getJSONObject("medium");
String video_id = jsonVideoId.getString("videoId");
VideoDetails vd = new VideoDetails();
vd.setVideoId(video_id);
vd.setTitle(jsonObjectSnippet.getString("title"));
vd.setDescription(jsonObjectSnippet.getString("description"));
vd.setUrl(jsonObjectDefault.getString("url"));
videoDetailsoArrayList.add(vd);
}
}
}
}
}catch (JSONException e) {
e.printStackTrace();
}
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
adapter= new adapter(getApplicationContext(),videoDetailsoArrayList);
recyclerView.setAdapter(adapter);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),error.getMessage(), LENGTH_LONG).show();
}
});
requestQueue.add(stringRequest);
}
Now I am trying to change the channelID from the String url of MainActivity2 such that when itemview with String channelnames "PTC Punjabi" is clicked, the MainActivity is loaded with channelID "UCHJW1_0oPzYZl89wX_jhrgA", when channelnames "Chakde Tv" is clicked, the MainActivity2 is loaded with
channelID "UCaT-WGdJLyEDnxZPAKRTbqQ" and so on. but I dont understand how to pass the list of channelId to MainActivity2?
Should I declare channelId array in MainActivity?. Please somebody guide me in this step. I know the solution is small as I have seen tutorials on button activities but I cant understand passing url to other activity.
channel model class
public class channel {
String channelname;
int channelimage;
public channel(String channelname, int channelimage) {
this.channelname = channelname;
this.channelimage = channelimage;
}
public String getChannelname() {
return channelname;
}
public int getChannelimage() {
return channelimage;
}
}
First of all: it's not a good practice to create Intent somewhere else then Activity of which intent your are creating.
So you need to add static method in your MainActivity2:
public static String CHANNEL_ID_EXTRA = "channel_id_extra";
public static Intent newIntent(Context context, String channelID) {
return new Intent(context, MainActivity2.class).putExtra(CHANNEL_ID_EXTRA, channelID);
}
After that you can get this ID in onCreate() method by :
final String channelId = getIntent().getStringExtra(CHANNEL_ID_EXTRA);
And now in Holder: EDITED HERE
#Override
public void onBindViewHolder(#NonNull Channelviewholder holder, int position) {
final channel channel=channelList.get(position);
holder.channelname.setText(channel.getChannelname());
holder.channelimage.setImageResource(channel.getChannelimage());
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClickListener(View v, int position) {
final String channelID= channelList.get(position);
Intent intent=MainActivity2.newIntent(v.getContext(), channelID);
v.getContext().startActivity(intent);
}
});
}
I was trying to implement Admob native ads inside my recyclerView, And i ended with below error & i have also attached my code. i even followed Google Code Lab. Still i ended with multiple error.
How do i add native ad's between <Arraylist>.
FYI: i have minimized code to be readable.
MainActivity:
public class MainActivity extends AppCompatActivity {
public static final int NUMBER_OF_ADS = 5;
AdLoader adLoader;
#BindView(R.id.recyclerView) RecyclerView recyclerView;
ArrayList<VideoModel> arrayListVideos;
ArrayList<UnifiedNativeAd> nativeAds = new ArrayList<>();
private VideoAdapter videoAdapter;
private AdView mAdView;
private ShimmerFrameLayout shimmerFrameLayout;
private GridLayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int autoCardWith = DisplayUtils.calculateNoOfColumns(getApplicationContext());
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
adMob();
arrayListVideos = new ArrayList<>();
mLayoutManager = new GridLayoutManager(this, autoCardWith);
//mLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
// #Override
//public int getSpanSize(int position) { if (position % MainActivity.ITEMS_PER_AD == 0) { return autoCardWith; } return 1; }
//});
recyclerView.setHasFixedSize(true);
//recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setLayoutManager(new GridLayoutManager(this, autoCardWith));
recyclerView.setHasFixedSize(true);
shimmerFrameLayout = findViewById(R.id.shimmer_view);
shimmerFrameLayout.setVisibility(View.VISIBLE);
shimmerFrameLayout.startShimmer();
recyclerView.setVisibility(View.INVISIBLE);
askPermission();
displayAllVideos();
loadNativeAds();
}
private void loadNativeAds() {
AdLoader.Builder builder = new AdLoader.Builder(this,getResources().getString(R.string.native_ad_id));
adLoader = builder.forUnifiedNativeAd(new UnifiedNativeAd.OnUnifiedNativeAdLoadedListener() {
#Override
public void onUnifiedNativeAdLoaded(UnifiedNativeAd unifiedNativeAd) {
nativeAds.add(unifiedNativeAd);
if (!adLoader.isLoading()) {
insertAdsinMenuItem();
}
}
}).withAdListener(new AdListener() {
#Override
public void onAdFailedToLoad(int i) {
super.onAdFailedToLoad(i);
if (!adLoader.isLoading()) {
insertAdsinMenuItem();
}
}
}).build();
adLoader.loadAds(new AdRequest.Builder().build(),NUMBER_OF_ADS);
}
private void insertAdsinMenuItem() {
if (nativeAds.size() < 0 ){
return;
}
int offset = (arrayListVideos.size() / nativeAds.size() + 1 );
int index = 0;
for (UnifiedNativeAd ad:nativeAds){
arrayListVideos.add(index,ad);
index = index + offset;
}
}
private void adMob() {
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
mAdView = findViewById(R.id.main_banner);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
}
private void askPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)){
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:"+getPackageName()));
startActivityForResult(intent,2084);
}
}
private void displayAllVideos() {
Uri uri;
Cursor cursor;
int column_index_data,thum;
String absolutePathThumb;
uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.MediaColumns.DATA, MediaStore.Video.Media.BUCKET_DISPLAY_NAME, MediaStore.Video.Media._ID,MediaStore.Video.Thumbnails.DATA};
final String orderBy = MediaStore.Video.Media.DEFAULT_SORT_ORDER;
cursor = getApplicationContext().getContentResolver().query(uri,projection,null,null,orderBy);
column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
thum = cursor.getColumnIndexOrThrow(MediaStore.Video.Thumbnails.DATA);
while (cursor.moveToNext()){
Log.d("VIDEO", cursor.getString(0));
absolutePathThumb = cursor.getString(column_index_data);
Uri thumbUri = Uri.fromFile(new File(absolutePathThumb));
//String cursorThumb = cursor.getString(thum);
String fileName = FilenameUtils.getBaseName(absolutePathThumb);
String extension = FilenameUtils.getExtension(absolutePathThumb);
String duration = getDuration(absolutePathThumb);
VideoModel videoModel = new VideoModel();
videoModel.setDuration(duration);
videoModel.setVideo_uri(thumbUri.toString());
videoModel.setVideo_path(absolutePathThumb);
videoModel.setVideo_name(fileName);
videoModel.setVideo_thumb(cursor.getString(thum));
if (extension!=null){
videoModel.setVideo_extension(extension);
}else {
videoModel.setVideo_extension("mp4");
}
if (duration!=null){
videoModel.setDuration(duration);
}else {
videoModel.setDuration("00:00");
}
arrayListVideos.add(videoModel);
}
videoAdapter = new VideoAdapter(this,arrayListVideos);
shimmerFrameLayout.setVisibility(View.INVISIBLE);
shimmerFrameLayout.stopShimmer();
recyclerView.setVisibility(View.VISIBLE);
recyclerView.setAdapter(videoAdapter);
//set adapter
}
}
VideoAdapter:
public class VideoAdapter extends RecyclerView.Adapter<VideoAdapter.VideoAdapterViewHolder> implements Filterable {
private final int MENU_ITEM_VIEW_TYPE = 0;
private final int UNIFIED_NATIVE_AD_VIEW_TYPE = 1;
Context context;
ArrayList<VideoModel> arrayListVideo;
ArrayList<VideoModel> arrayListVideoAll;
private Activity mainActivity;
public VideoAdapter(Context context, ArrayList<VideoModel> arrayListVideos){
this.context = context;
this.arrayListVideo = arrayListVideos;
arrayListVideoAll = new ArrayList<>(arrayListVideo);
mainActivity = (Activity) context;
}
#NonNull
#Override
public VideoAdapterViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
switch (i){
case UNIFIED_NATIVE_AD_VIEW_TYPE:
View unifiedNativeLayoutView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.ad_unified,viewGroup,false);
return new UnifiedNativeAdViewHolder(unifiedNativeLayoutView);
case MENU_ITEM_VIEW_TYPE:
default:
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_videos,viewGroup,false);
return new VideoAdapterViewHolder(view);
}
}
#Override
public void onBindViewHolder(#NonNull VideoAdapterViewHolder videoAdapterViewHolder, int i) {
int viewType = getItemViewType(i);
switch (viewType){
case UNIFIED_NATIVE_AD_VIEW_TYPE:
UnifiedNativeAd unifiedNativeAd = (UnifiedNativeAd)arrayListVideo.get(i);
populateNativeAdView(unifiedNativeAd,((UnifiedNativeAdViewHolder)videoAdapterViewHolder).getAdView());
break;
case MENU_ITEM_VIEW_TYPE:
Glide.with(context).load(arrayListVideo.get(i).getVideo_thumb()).into(videoAdapterViewHolder.image);
videoAdapterViewHolder.name.setText(arrayListVideo.get(i).getVideo_name() + "." + arrayListVideo.get(i).getVideo_extension());
videoAdapterViewHolder.duration.setText(arrayListVideo.get(i).getDuration());
}
}
#Override
public int getItemCount() {
return arrayListVideo.size();
}
public class VideoAdapterViewHolder extends RecyclerView.ViewHolder{
public ImageView image;
public TextView name,duration;
public ImageView videoOption;
public VideoAdapterViewHolder(#NonNull View itemView) {
super(itemView);
if (!(itemView instanceof AdView)) {
image = (ImageView)itemView.findViewById(R.id.vid_image);
name = (TextView)itemView.findViewById(R.id.vid_name);
duration = (TextView)itemView.findViewById(R.id.vid_duration);
videoOption = (ImageView) itemView.findViewById(R.id.video_option);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
VideoModel videoModel = arrayListVideo.get(getAdapterPosition());
((MainActivity)context).openVideoPlayerActivity(videoModel);
}
});
videoOption.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
VideoModel videoModel = arrayListVideo.get(getAdapterPosition());
((MainActivity)context).VideoMoreOption(videoModel);
}
});
}
}
}
private void populateNativeAdView(UnifiedNativeAd unifiedNativeAd, UnifiedNativeAdView adView) {
((TextView)adView.getHeadlineView()).setText(unifiedNativeAd.getHeadline());
((TextView)adView.getBodyView()).setText(unifiedNativeAd.getBody());
((TextView)adView.getCallToActionView()).setText(unifiedNativeAd.getCallToAction());
NativeAd.Image icon = unifiedNativeAd.getIcon();
if (icon==null){
adView.getIconView().setVisibility(View.INVISIBLE);
}else {
((ImageView)adView.getIconView()).setImageDrawable(icon.getDrawable());
adView.getIconView().setVisibility(View.VISIBLE);
}
if(unifiedNativeAd.getPrice()==null){
adView.getPriceView().setVisibility(View.INVISIBLE);
}else {
adView.getPriceView().setVisibility(View.VISIBLE);
((TextView)adView.getPriceView()).setText(unifiedNativeAd.getPrice());
}
if(unifiedNativeAd.getStarRating()==null){
adView.getStarRatingView().setVisibility(View.INVISIBLE);
}else {
adView.getStarRatingView().setVisibility(View.VISIBLE);
((RatingBar)adView.getStarRatingView()).setRating(unifiedNativeAd.getStarRating().floatValue());
}
if(unifiedNativeAd.getAdvertiser()==null){
adView.getAdvertiserView().setVisibility(View.INVISIBLE);
}else {
adView.getAdvertiserView().setVisibility(View.VISIBLE);
((TextView)adView.getAdvertiserView()).setText(unifiedNativeAd.getAdvertiser());
}
adView.setNativeAd(unifiedNativeAd);
}
}
public class VideoAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements Filterable {
private final int MENU_ITEM_VIEW_TYPE = 0;
private final int UNIFIED_NATIVE_AD_VIEW_TYPE = 1;
Context context;
ArrayList<Object> arrayListVideo;
ArrayList<Object> arrayListVideoAll;
private Activity mainActivity;
public VideoAdapter(Context context, ArrayList<Object> arrayListVideos) {
this.context = context;
this.arrayListVideo = arrayListVideos;
arrayListVideoAll = new ArrayList<>(arrayListVideo);
mainActivity = (Activity) context;
}
#Override
public int getItemViewType(int position) {
if(arrayListVideo.get(position) instanceof VideoModel){
return MENU_ITEM_VIEW_TYPE;
} else{
return UNIFIED_NATIVE_AD_VIEW_TYPE;
}
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
switch (i) {
case UNIFIED_NATIVE_AD_VIEW_TYPE:
View unifiedNativeLayoutView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.ad_unified, viewGroup, false);
return new UnifiedNativeAdViewHolder(unifiedNativeLayoutView);
case MENU_ITEM_VIEW_TYPE:
default:
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_videos, viewGroup, false);
return new VideoAdapterViewHolder(view);
}
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder viewHolder, int i) {
switch (viewHolder.getItemViewType()) {
case UNIFIED_NATIVE_AD_VIEW_TYPE:
UnifiedNativeAd unifiedNativeAd = (UnifiedNativeAd) arrayListVideo.get(i);
populateNativeAdView(unifiedNativeAd, ((UnifiedNativeAdViewHolder) viewHolder).getAdView());
break;
case MENU_ITEM_VIEW_TYPE:
final VideoAdapterViewHolder videoAdapterViewHolder = (VideoAdapterViewHolder) viewHolder;
final VideoModel item = (VideoModel) arrayListVideo.get(i);
Glide.with(context).load(item.getVideo_thumb()).into(videoAdapterViewHolder.image);
videoAdapterViewHolder.name.setText(item.getVideo_name() +
"." + item.getVideo_extension());
videoAdapterViewHolder.duration.setText(item.getDuration());
}
}
#Override
public int getItemCount() {
return arrayListVideo.size();
}
#Override
public Filter getFilter() {
return null;
}
public class VideoAdapterViewHolder extends RecyclerView.ViewHolder {
public ImageView image;
public TextView name, duration;
public ImageView videoOption;
public VideoAdapterViewHolder(#NonNull View itemView) {
super(itemView);
if (!(itemView instanceof AdView)) {
image = (ImageView) itemView.findViewById(R.id.vid_image);
name = (TextView) itemView.findViewById(R.id.vid_name);
duration = (TextView) itemView.findViewById(R.id.vid_duration);
videoOption = (ImageView) itemView.findViewById(R.id.video_option);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
VideoModel videoModel = (VideoModel) arrayListVideo.get(getAdapterPosition());
((MainActivity) context).openVideoPlayerActivity(videoModel);
}
});
videoOption.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
VideoModel videoModel = (VideoModel) arrayListVideo.get(getAdapterPosition());
((MainActivity) context).VideoMoreOption(videoModel);
}
});
}
}
}
private void populateNativeAdView(UnifiedNativeAd unifiedNativeAd, UnifiedNativeAdView adView) {
((TextView) adView.getHeadlineView()).setText(unifiedNativeAd.getHeadline());
((TextView) adView.getBodyView()).setText(unifiedNativeAd.getBody());
((TextView) adView.getCallToActionView()).setText(unifiedNativeAd.getCallToAction());
NativeAd.Image icon = unifiedNativeAd.getIcon();
if (icon == null) {
adView.getIconView().setVisibility(View.INVISIBLE);
} else {
((ImageView) adView.getIconView()).setImageDrawable(icon.getDrawable());
adView.getIconView().setVisibility(View.VISIBLE);
}
if (unifiedNativeAd.getPrice() == null) {
adView.getPriceView().setVisibility(View.INVISIBLE);
} else {
adView.getPriceView().setVisibility(View.VISIBLE);
((TextView) adView.getPriceView()).setText(unifiedNativeAd.getPrice());
}
if (unifiedNativeAd.getStarRating() == null) {
adView.getStarRatingView().setVisibility(View.INVISIBLE);
} else {
adView.getStarRatingView().setVisibility(View.VISIBLE);
((RatingBar) adView.getStarRatingView()).setRating(unifiedNativeAd.getStarRating().floatValue());
}
if (unifiedNativeAd.getAdvertiser() == null) {
adView.getAdvertiserView().setVisibility(View.INVISIBLE);
} else {
adView.getAdvertiserView().setVisibility(View.VISIBLE);
((TextView) adView.getAdvertiserView()).setText(unifiedNativeAd.getAdvertiser());
}
adView.setNativeAd(unifiedNativeAd);
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
public static final int NUMBER_OF_ADS = 5;
AdLoader adLoader;
#BindView(R.id.recyclerView)
RecyclerView recyclerView;
ArrayList<Object> arrayListVideos;
ArrayList<UnifiedNativeAd> nativeAds = new ArrayList<>();
private VideoAdapter videoAdapter;
private AdView mAdView;
private ShimmerFrameLayout shimmerFrameLayout;
private GridLayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int autoCardWith = DisplayUtils.calculateNoOfColumns(getApplicationContext());
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
adMob();
arrayListVideos = new ArrayList<>();
mLayoutManager = new GridLayoutManager(this, autoCardWith);
//mLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
// #Override
//public int getSpanSize(int position) { if (position % MainActivity.ITEMS_PER_AD == 0) { return autoCardWith; } return 1; }
//});
recyclerView.setHasFixedSize(true);
//recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setLayoutManager(new GridLayoutManager(this, autoCardWith));
recyclerView.setHasFixedSize(true);
shimmerFrameLayout = findViewById(R.id.shimmer_view);
shimmerFrameLayout.setVisibility(View.VISIBLE);
shimmerFrameLayout.startShimmer();
recyclerView.setVisibility(View.INVISIBLE);
askPermission();
displayAllVideos();
loadNativeAds();
}
private void loadNativeAds() {
AdLoader.Builder builder = new AdLoader.Builder(this,getResources().getString(R.string.native_ad_id));
adLoader = builder.forUnifiedNativeAd(new UnifiedNativeAd.OnUnifiedNativeAdLoadedListener() {
#Override
public void onUnifiedNativeAdLoaded(UnifiedNativeAd unifiedNativeAd) {
nativeAds.add(unifiedNativeAd);
if (!adLoader.isLoading()) {
insertAdsinMenuItem();
}
}
}).withAdListener(new AdListener() {
#Override
public void onAdFailedToLoad(int i) {
super.onAdFailedToLoad(i);
if (!adLoader.isLoading()) {
insertAdsinMenuItem();
}
}
}).build();
adLoader.loadAds(new AdRequest.Builder().build(),NUMBER_OF_ADS);
}
private void insertAdsinMenuItem() {
if (nativeAds.size() < 0 ){
return;
}
int offset = (arrayListVideos.size() / nativeAds.size() + 1 );
int index = 0;
for (UnifiedNativeAd ad:nativeAds){
arrayListVideos.add(index,ad);
index = index + offset;
}
}
private void adMob() {
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
mAdView = findViewById(R.id.main_banner);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
}
private void askPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)){
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:"+getPackageName()));
startActivityForResult(intent,2084);
}
}
private void displayAllVideos() {
Uri uri;
Cursor cursor;
int column_index_data,thum;
String absolutePathThumb;
uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.MediaColumns.DATA, MediaStore.Video.Media.BUCKET_DISPLAY_NAME, MediaStore.Video.Media._ID,MediaStore.Video.Thumbnails.DATA};
final String orderBy = MediaStore.Video.Media.DEFAULT_SORT_ORDER;
cursor = getApplicationContext().getContentResolver().query(uri,projection,null,null,orderBy);
column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
thum = cursor.getColumnIndexOrThrow(MediaStore.Video.Thumbnails.DATA);
while (cursor.moveToNext()){
Log.d("VIDEO", cursor.getString(0));
absolutePathThumb = cursor.getString(column_index_data);
Uri thumbUri = Uri.fromFile(new File(absolutePathThumb));
//String cursorThumb = cursor.getString(thum);
String fileName = FilenameUtils.getBaseName(absolutePathThumb);
String extension = FilenameUtils.getExtension(absolutePathThumb);
String duration = getDuration(absolutePathThumb);
VideoModel videoModel = new VideoModel();
videoModel.setDuration(duration);
videoModel.setVideo_uri(thumbUri.toString());
videoModel.setVideo_path(absolutePathThumb);
videoModel.setVideo_name(fileName);
videoModel.setVideo_thumb(cursor.getString(thum));
if (extension!=null){
videoModel.setVideo_extension(extension);
}else {
videoModel.setVideo_extension("mp4");
}
if (duration!=null){
videoModel.setDuration(duration);
}else {
videoModel.setDuration("00:00");
}
arrayListVideos.add(videoModel);
}
videoAdapter = new VideoAdapter(this,arrayListVideos);
shimmerFrameLayout.setVisibility(View.INVISIBLE);
shimmerFrameLayout.stopShimmer();
recyclerView.setVisibility(View.VISIBLE);
recyclerView.setAdapter(videoAdapter);
//set adapter
}
}
I tried all the possible options that I just found.
I can’t send ArrayList to another activity via the Parcelable interface.
To implement a media player
String format information it sends.
I would be very grateful, maybe there are some other options. This is the first time I'm asking a question here
Here is my activity that I use to send, the code is still very raw
public class MainActivity extends AppCompatActivity {
ScheduledExecutorService scheduledExecutorService;
public MediaPlayer mediaPlayer;
private SeekBar seekBar;
private ImageView btn_Play;
private ImageView btn_Next;
private ImageView btn_Pre;
private TextView setCurrentDuration, setTotalDuration;
private ArrayList<SoundInfo> audioList = new ArrayList<>();
SoundAdapter adapter = new SoundAdapter();
public Handler handler = new Handler();
AudioEffect audioEffect;
private int currentPosition = 0;
private SoundInfo soundInfo = new SoundInfo(this);
SoundEffects soundEffects;
boolean mediaPauseStat = false;
Context context;
PageFragmentOne pageFragmentOne;
//public MainActivity(PageFragmentOne pageFragmentOne) {
// this.pageFragmentOne = pageFragmentOne;
//}
MediaManager mediaManager = new MediaManager(this, adapter, audioList);
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Старт сервиса
//Intent i = new Intent(this, MediaPlaybackService.class);
//i.putExtra("play", "письмо от главного активити");
//startService(i);
//mediaManager.LoadSounds();
/**
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
**/
////////////////////////////////////////////////////////////////////////////////////////////
setCurrentDuration = findViewById(R.id.current_Duration);
setTotalDuration = findViewById(R.id.total_Duration);
seekBar = findViewById(R.id.seekBar);
RecyclerView list = findViewById(R.id.my_recycler_view);
list.setAdapter(adapter);
list.setLayoutManager(new LinearLayoutManager(this));
// Оформление отображения адаптера
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(this, LinearLayout.VERTICAL);
dividerItemDecoration.setDrawable(getResources().getDrawable(R.drawable.list_item_divider, null));
list.addItemDecoration(dividerItemDecoration);
///////////////////////////////////////////////
soundInfo.setMassive(audioList);
adapter.setOnItemClickListener(new SoundAdapter.OnItemClickListener() {
#Override
public void onClick(View v, final SoundInfo obj, final int position, final ImageView onNext) {
final SoundInfo path = audioList.get(position);
String audioPath = obj.getData();
prepareMedia(position);
// Задаем текующию позицию трека
currentPosition = position;
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
// TODO Auto-generated method stub
mediaPlayer.start();
// Всегда должен быть после старта плеера, что бы не вылазило 238
updateProgressBar();
//seekBar.setProgress(0);
seekBar.setMax(mediaPlayer.getDuration());
btn_Play.setImageResource(R.drawable.btn_pause);
}
});
// Перемотка аудио
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// Слишком часто обновляет
}
#Override
public void onStartTrackingTouch(final SeekBar seekBar) {
if (mediaPlayer != null) {
soundInfo.setMediaPauseStat(false);
soundInfo.setMediaRewind(false);
mediaPlayer.pause();
seekBar.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
mediaPlayer.seekTo(seekBar.getProgress());
return false;
}
});
}
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
if (mediaPlayer != null) {
soundInfo.setMediaPauseStat(true);
//soundInfo.setMediaRewind(true);
mediaPlayer.start();
}
}
});
// Кнопка проигрывания и паузы
btn_Play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!mediaPlayer.isPlaying()) {
onPlay();
} else {
onPaused();
}
}
});
// Следующий трек
btn_Next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onNext();
}
});
// Предыдущий трек
btn_Pre.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onPre();
}
});
}
});
init();
}
private MyBroadcastReceiver myReceiver;
#Override
public void onResume() {
super.onResume();
myReceiver = new MyBroadcastReceiver();
final IntentFilter intentFilter = new IntentFilter("YourAction");
LocalBroadcastManager.getInstance(this).registerReceiver(myReceiver, intentFilter);
}
#Override
public void onPause() {
super.onPause();
if (myReceiver != null)
LocalBroadcastManager.getInstance(this).unregisterReceiver(myReceiver);
myReceiver = null;
}
public class MyBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// String yourValue = b.getString("ser");
Bundle bundle = intent.getExtras();
}
}
public void onMainMediaPlayList(View view) {
final Intent intent2 = new Intent(getApplicationContext(), MainMediaPlayList.class);
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("MEDIA_MASSIVE", audioList);
intent2.putExtras(bundle);
startActivity(intent2);
//Intent i = new Intent(MainActivity.this, MediaPlaybackService.class);
//startService(i);
////////////////////////////////////////////////////////////////////////////////////////////
}
public void init() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Разрешение не предоставляется
// Должны ли мы показать объяснение?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
// Показать объяснение пользователю * асинхронно* -- не блокировать
// этот поток ждет ответа пользователя! После пользователя
// увидев объяснение, попробуйте еще раз запросить разрешение.
} else {
// Никаких объяснений не требуется; запросить разрешение
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.MODIFY_AUDIO_SETTINGS,
Manifest.permission.RECORD_AUDIO},
101);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS является
// app-определенная константа int. Метод обратного вызова получает
// результат запроса.
}
} else {
// Разрешение уже предоставлено
//loadSounds();
mediaManager.LoadSounds();
}
//bPlayPause = findViewById(R.id.bPlayPause);
//lv = (ListView) findViewById(R.id.lvPlayList);
btn_Play = findViewById(R.id.btn_Play);
btn_Next = findViewById(R.id.btn_Next);
btn_Pre = findViewById(R.id.btn_Pre);
}
Here is my SoundInfo
public class SoundInfo implements Parcelable {
private String data, artist, title;
private Context context;
private String pathData;
public SoundInfo(MainActivity context) {
this.context = context;
}
public SoundInfo() {
}
public SoundInfo(MainMediaPlayList context) {
this.context = context;
}
public SoundInfo(MediaPlaybackService mediaPlaybackService, String star) {
this.context = mediaPlaybackService;
this.star = star;
}
protected SoundInfo(Parcel in) {
data = in.readString();
artist = in.readString();
title = in.readString();
pathData = in.readString();
mediaPauseStat = in.readByte() != 0;
ismediaRewind = in.readByte() != 0;
audioList = in.createTypedArrayList(SoundInfo.CREATOR);
star = in.readString();
}
public static final Creator<SoundInfo> CREATOR = new Creator<SoundInfo>() {
#Override
public SoundInfo createFromParcel(Parcel in) {
return new SoundInfo(in);
}
#Override
public SoundInfo[] newArray(int size) {
return new SoundInfo[size];
}
};
public void SoundInfo(String data, String artist, String title) {
this.data = data;
this.artist = artist;
this.title = title;
}
public SoundInfo(String data, String artist, String title) {
this.data = data;
this.artist = artist;
this.title = title;
}
public String getData() {
return data;
}
public String getArtist() {
return artist;
}
public String getTitle() {
return title;
}
public void setData(String artist) {
this.data = data;
}
public void setArtist(String artist) {
this.artist = artist;
}
public void setTitle(String title) {
this.title = title;
}
public void setpathData(String pathData) {
this.pathData = pathData;
}
public String getpathData() {
return pathData;
}
// Запись в память для отображения времени
boolean mediaPauseStat = true;
boolean ismediaRewind = true;
public void setMediaPauseStat(boolean mediaPauseStat) {
this.mediaPauseStat = mediaPauseStat;
}
public boolean getMediaPauseStat() {
return mediaPauseStat;
}
public void setMediaRewind(boolean isMediaRewind) {
this.ismediaRewind = ismediaRewind;
}
public boolean getMediaRewind() {
return ismediaRewind;
}
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
// Массив
private ArrayList<SoundInfo> audioList = new ArrayList<SoundInfo>();
public ArrayList<SoundInfo> getMassive() {
return audioList;
}
public void setMassive(ArrayList<SoundInfo> audioList) {
this.audioList = audioList;
}
private String star;
public String getStar() {
return star;
}
public void setStar(String star) {
this.star = star;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(data);
dest.writeString(artist);
dest.writeString(title);
dest.writeString(pathData);
dest.writeByte((byte) (mediaPauseStat ? 1 : 0));
dest.writeByte((byte) (ismediaRewind ? 1 : 0));
dest.writeTypedList(audioList);
dest.writeString(star);
}
}
Here is my adater which I use
public class SoundAdapter extends RecyclerView.Adapter<SoundAdapter.ViewHolder> {
private ArrayList<SoundInfo> audioList = new ArrayList<SoundInfo>();
Context context;
//private String[] items;
private OnItemClickListener onItemClickListener;
public void setItems(Context context, ArrayList<SoundInfo> audioList) {
this.context = context;
this.audioList = audioList;
//audioList.addAll(items);
}
public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_audio, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int position) {
holder.bind(audioList.get(position));
holder.clickFile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final SoundInfo path = audioList.get(position);
onItemClickListener.onClick(view, path, position, holder.onNext);
}
});
}
#Override
public int getItemCount() {
return audioList == null ? 0 : audioList.size();
}
static class ViewHolder extends RecyclerView.ViewHolder {
private TextView data, title, artist;
private ImageView onNext;
private View clickFile;
ViewHolder(View view) {
super(view);
title = view.findViewById(R.id.tvSoundTitle);
artist = view.findViewById(R.id.tvSoundArtist);
clickFile = view.findViewById(R.id.clickFile);
//data = view.findViewById(R.id.item_title);
//onNext = view.findViewById(R.id.imageNext);
}
public void bind(SoundInfo soundInfo) {
title.setText(soundInfo.getTitle());
artist.setText(soundInfo.getArtist());
//clickFile.setText(soundInfo.getData());
}
}
// Передача данных в основной активити
public interface OnItemClickListener {
void onClick(View view, SoundInfo obj, int position, ImageView onNext);
}
}
Here is the second activity that an ArrayList gets.
Bundle bundle = getIntent().getExtras();
ArrayList<SoundInfo> audioList = bundle.getParcelableArrayList("MEDIA_MASSIVE");
adapter.setItems(MainMediaPlayList.this, audioList);
adapter.notifyDataSetChanged();
// загрузка адаптера
RecyclerView list = findViewById(R.id.my_recycler_view);
list.setAdapter(adapter);
list.setLayoutManager(new LinearLayoutManager(MainMediaPlayList.this));
When you open a new activity, the application crashes
does not display any errors in the log, the problem is as I understand that intent can not find
audioList as it seems to me
If I remove the method everything loads
public void onMainMediaPlayList(View view) {
final Intent intent2 = new Intent(getApplicationContext(), MainMediaPlayList.class);
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("MEDIA_MASSIVE", audioList);
intent2.putExtras(bundle);
startActivity(intent2);
Here I took off the launch log, it may somehow help
2020-03-08 18:09:43.406 15730-15730/com.shimmer.myapplication W/r.myapplicatio: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
2020-03-08 18:09:43.406 15730-15730/com.shimmer.myapplication W/r.myapplicatio: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
2020-03-08 18:09:43.431 15730-15730/com.shimmer.myapplication I/OverScrollerOptimization: start init SmartSlideOverScroller and get the overscroller config
2020-03-08 18:09:43.431 15730-15730/com.shimmer.myapplication I/OverScrollerOptimization: get the overscroller config
2020-03-08 18:09:43.466 15730-15730/com.shimmer.myapplication D/HwFrameworkSecurityPartsFactory: HwFrameworkSecurityPartsFactory in.
2020-03-08 18:09:43.466 15730-15730/com.shimmer.myapplication I/HwFrameworkSecurityPartsFactory: add HwFrameworkSecurityPartsFactory to memory.
2020-03-08 18:09:43.506 15730-15730/com.shimmer.myapplication D/ActivityThread: add activity client record, r= ActivityRecord{e3185e4 token=android.os.BinderProxy#837d3d7 {com.shimmer.myapplication/com.shimmer.myapplication.MainActivity}} token= android.os.BinderProxy#837d3d7
I don't think so, You can send an ArrayList like this.
I recommend you sending Class instead of sending an Arraylist.
So, just create a class like AudiolistHolder and put your ArrayList inside this class and don't forget to implement Parcelable interface for this class, too, and send this class between activities this should solve your problem. I always use this way.
EDIT:
You can use this to send your data
Intent intent2 = new Intent(this, MainMediaPlayList.class);
MassiveAudioList m = new MassiveAudioList(audioList);
intent2.putExtra("MEDIA_MASSIVE”, m);
startActivity(intent2);
and you can use this in your second activity to retrieve data
MassiveAudioList massiveAudio=getIntent().getParcelableExtra("MEDIA_MASSIVE");
ArrayList<SoundInfo> audioList = massiveAudio.getMassiveAudioList();
Have you tried like this with arraylist
I think it can be,
In MainActivity.java
ArrayList<String> audioList= new ArrayList<>();
audioList.add("ChipThrills");
Intent i = new Intent(MainActivity.this, Secondactivity.class);
i.putExtra("Musickey", audioList);
startActivity(i);
In SecondActivity.java
ArrayList<String> audioList = (ArrayList<String>) getIntent().getSerializableExtra("Musickey");
I am writing to you here because I did not understand how to add code to the comment
And how do I extract data by adding it to an array. If of course I did the right thing, I'm new to this field. Thanks.
public class MassiveAudioList implements Parcelable {
private ArrayList<SoundInfo> audioList = new ArrayList<>();
private Context context;
public MassiveAudioList(Context context) {
this.context = context;
}
public MassiveAudioList(ArrayList audioList) {
this.audioList = audioList;
}
protected MassiveAudioList(Parcel in) {
audioList = in.createTypedArrayList(SoundInfo.CREATOR);
}
public static final Creator<MassiveAudioList> CREATOR = new Creator<MassiveAudioList>() {
#Override
public MassiveAudioList createFromParcel(Parcel in) {
return new MassiveAudioList(in);
}
#Override
public MassiveAudioList[] newArray(int size) {
return new MassiveAudioList[size];
}
};
public ArrayList<SoundInfo> getMassiveAudioList() {
return audioList;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeTypedList(audioList);
}
}
public void onMainMediaPlayList(View view) {
Log.d("TAG", "soundinfo" + soundInfo.getData());
final Intent intent2 = new Intent(getApplicationContext(), MainMediaPlayList.class);
massiveAudioList = new MassiveAudioList(this);
MassiveAudioList m = new MassiveAudioList(audioList);
Bundle bundle = new Bundle();
bundle.putParcelable("MEDIA_MASSIVE", m);
intent2.putExtras(bundle);
startActivity(intent2);
}
i am trying implement search function in my section recyclerview
its not working but also not showing error...
i try with edittext addTextChangedListener method.
then in adapter add notifydatachanged method.
try with normal recyclerview its working fine but when use with section recyclerview its not working
sorry for bad english
here is mainActivty
here i get data from server and pass to the adapter in this class i am add the method for filter recyclerview
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_section_rv_search_prac);
init();
initView();
setUpRecyclerView();
tempModels = new ArrayList<TempModel>();
serviceRequest();
searchItem();
}
private void init() {
mAdapter = new ItemRecyclerViewAdapter(SectionRvSearchPrac.this);
}
private void initView() {
mEt_search = findViewById(R.id.et_search_main);
}
///////////////////////////////
private void searchItem() {
mEt_search.addTextChangedListener(
new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
#Override
public void afterTextChanged(Editable s) {
filter(s.toString());
}
});
}
//method for filter list is here..
private void filter(String text) {
ArrayList<TempModel> mFilter_list = new ArrayList<>();
for (TempModel tempModel : tempModels) {
if (tempModel.getName().toLowerCase().contains(text.toLowerCase())) {
mFilter_list.add(tempModel);
}
}
Log.d(TAG, "filter: " + mFilter_list);
mAdapter.filterList(mFilter_list);
}
//////////////////
private void setUpRecyclerView() {
recyclerView = (RecyclerView) findViewById(R.id.sectioned_recycler_view);
recyclerView.setHasFixedSize(true);
linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
}
private void serviceRequest() {
StringRequest stringRequest =
new StringRequest(
Request.Method.GET,
JSON_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
parseJason(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// displaying the error in toast if occurrs
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT)
.show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
public void parseJason(String response) {
{
Log.d(TAG, "onResponse: " + response);
String[] first;
ArrayList<String> sewction_list = new ArrayList<>();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("data");
String data = jsonArray.getString(0);
first = data.split(Pattern.quote("***^^^***"));
myList_sec = new ArrayList<>(Arrays.asList(first));
for (int j = 0; j < myList_sec.size(); j++) {
myList_first =
new ArrayList<>(Arrays.asList(myList_sec.get(j).split(Pattern.quote("^^^^"))));
sewction_list.add(myList_first.get(0));
myList_second =
new ArrayList<>(Arrays.asList(myList_first.get(1).split(Pattern.quote("^^"))));
ArrayList<String> id = new ArrayList<>();
ArrayList<String> url = new ArrayList<>();
ArrayList<String> img = new ArrayList<>();
ArrayList<String> name = new ArrayList<>();
for (int i = 0; i < myList_second.size(); i++) {
myList_third =
new ArrayList<>(Arrays.asList(myList_second.get(i).split(Pattern.quote("**"))));
url.add(myList_third.get(0));
img.add(myList_third.get(1));
name.add(myList_third.get(2));
id.add(myList_third.get(3));
tempModels.add(
new TempModel(
myList_third.get(2),
myList_third.get(0),
myList_third.get(1),
myList_third.get(3)));
}
sectionModelArrayList.add(new SectionModel(sewction_list, tempModels));
SectionRecyclerViewAdapter adapter =
new SectionRecyclerViewAdapter(
SectionRvSearchPrac.this, recyclerViewType, sectionModelArrayList);
recyclerView.setAdapter(adapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
here is myitemadapter class for child item
public class ItemRecyclerViewAdapter
extends RecyclerView.Adapter<ItemRecyclerViewAdapter.ItemViewHolder> {
private static final String TAG = "adapter";
private Context context;
ArrayList<TempModel> tempModels;
public ItemRecyclerViewAdapter(Context context) {
this.context = context;
}
public void setData(ArrayList<TempModel> data) {
this.tempModels = data;
}
#Override
public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view =
LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_custom_row_layout, parent, false);
return new ItemViewHolder(view);
}
#Override
public void onBindViewHolder(ItemViewHolder holder, final int position) {
String path = tempModels.get(position).getImage();
holder.itemLabel.setText(tempModels.get(position).getName());
Picasso.get().load(path).into(holder.imageView);
holder.cardView.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {}
});
}
#Override
public int getItemCount() {
return tempModels.size();
}
/// here method for update filter list
public void filterList(ArrayList<TempModel> filterdNames) {
this.tempModels = filterdNames;
notifyDataSetChanged();
}
class ItemViewHolder extends RecyclerView.ViewHolder {
private TextView itemLabel;
ImageView imageView;
CardView cardView;
public ItemViewHolder(View itemView) {
super(itemView);
itemLabel = (TextView) itemView.findViewById(R.id.item_label);
cardView = itemView.findViewById(R.id.cardview);
imageView = itemView.findViewById(R.id.img);
}
}
section model for section item
public class SectionModel {
private ArrayList<String> sectionLabel;
private ArrayList<TempModel> tempModels;
public SectionModel(ArrayList<String> sectionLabel, ArrayList<TempModel> tempModels) {
this.sectionLabel = sectionLabel;
this.tempModels = tempModels;
}
public ArrayList<String> getSectionLabel() {
return sectionLabel;
}
public ArrayList<TempModel> getTempModels() {
return tempModels;
}
}
model class for item
public class TempModel implements Parcelable{
String name;
String url;
String image;
String num;
public TempModel() {
}
public TempModel(String name, String url, String image, String num) {
this.name = name;
this.url = url;
this.image = image;
this.num = num;
}
protected TempModel(Parcel in) {
name = in.readString();
url = in.readString();
image = in.readString();
num = in.readString();
}
public static final Creator<TempModel> CREATOR = new Creator<TempModel>() {
#Override
public TempModel createFromParcel(Parcel in) {
return new TempModel(in);
}
#Override
public TempModel[] newArray(int size) {
return new TempModel[size];
}
};
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(url);
dest.writeString(image);
dest.writeString(num);
}
}
sectionadapter class
public class SectionRecyclerViewAdapter
extends RecyclerView.Adapter<SectionRecyclerViewAdapter.SectionViewHolder> {
private static final String TAG = "section";
class SectionViewHolder extends RecyclerView.ViewHolder {
private TextView sectionLabel, showAllButton;
private RecyclerView itemRecyclerView;
public SectionViewHolder(View itemView) {
super(itemView);
sectionLabel = (TextView) itemView.findViewById(R.id.section_label);
itemRecyclerView = (RecyclerView) itemView.findViewById(R.id.item_recycler_view);
}
}
private Context context;
private RecyclerViewType recyclerViewType;
private ArrayList<SectionModel> sectionModelArrayList;
public SectionRecyclerViewAdapter(
Context context,
RecyclerViewType recyclerViewType,
ArrayList<SectionModel> sectionModelArrayList) {
this.context = context;
this.recyclerViewType = recyclerViewType;
this.sectionModelArrayList = sectionModelArrayList;
}
#Override
public SectionViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rrow, parent, false);
return new SectionViewHolder(view);
}
#Override
public void onBindViewHolder(SectionViewHolder holder, int position) {
final SectionModel sectionModel = sectionModelArrayList.get(position);
holder.sectionLabel.setText(sectionModel.getSectionLabel().get(position));
// recycler view for items
holder.itemRecyclerView.setHasFixedSize(true);
holder.itemRecyclerView.setNestedScrollingEnabled(false);
GridLayoutManager gridLayoutManager = new GridLayoutManager(context, 3);
holder.itemRecyclerView.setLayoutManager(gridLayoutManager);
/* set layout manager on basis of recyclerview enum type */
ItemRecyclerViewAdapter adapter = new ItemRecyclerViewAdapter(context);
adapter.setData(sectionModel.getTempModels());
holder.itemRecyclerView.setAdapter(adapter);
}
#Override
public int getItemCount() {
return sectionModelArrayList.size();
}
Your code very confusing so i just write my solution.
public class SomeAdapter extends RecyclerView.Adapter<SomeAdapter.SomeViewHolder> implements Filterable{
...
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
mMainList = mYourJSONResponseList;
FilterResults results = new FilterResults();
ArrayList<YourModel> mFilter_list = new ArrayList<>();
//Place your logic
for (YourModel model : mMainList) {
if(model.getName().
toLowerCase().contains(text.toLowerCase())) {
mFilter_list.add(model);
}
}
results.count = mFilter_list.size();
results.values = mFilter_list;
return results;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
mMainList = (ArrayList<YourModel>) filterResults.values;
notifyDataSetChanged();
}
};
return filter;
}
And add this into your text listener
#Override
public void afterTextChanged(Editable s) {
//Add this
adapter.getFilter().filter(s.toString())
}
NOTE!! You will show mMainList only this list in your RecyclerView, And check nullpointerexceptions
I am using a ViewPager to be able to swipe between views. The problem that I am facing is, the first page does not render properly(only the static members from layout file get rendered), but the second page and further pages are rendered properly. Also, when I go to third or later page and then come swiping back to the first page, it gets rendered perfectly.
I know that ViewPager loads the first page as well second page in the beginning and does the same for every next page. Is this the reason why my first page is not rendered properly? I am making a network call on each page and the data returned is being displayed on the page.
Here is the code for my Adapter:
public class SlidingImageDetailAdapter extends PagerAdapter implements GoogleApiClient.OnConnectionFailedListener {
Context context;
List<ImageDetailData> list;
List<LatestComment> latestComments;
LayoutInflater layoutInflater;
GaApplication application;
protected GoogleApiClient mGoogleApiClient;
TinyDB tinyDB;
MixpanelAPI mixpanel;
RestAdapter restAdapter;
public final String TAG = getClass().getSimpleName();
private static int radius = Utils.dpToPx(40);
private String googlePlaceId = null;
private String finalPlace = null;
private String commentId = null;
private String imageId = null;
private String imageUrl = null;
private boolean updateNeeded;
private PlaceAutocompleteAdapter mAdapter;
ImageGalleryAdapter imageGalleryAdapter;
ImageCommentAdapter imageCommentAdapter;
ViewHolder holder = null;
private static final LatLngBounds BOUNDS_GREATER_SYDNEY = new LatLngBounds(
new LatLng(-34.041458, 150.790100), new LatLng(-33.682247, 151.383362));
public SlidingImageDetailAdapter(Context context, List<ImageDetailData> list) {
this.context = context;
this.list = list;
layoutInflater = LayoutInflater.from(context);
application = (GaApplication) ((AppCompatActivity) context).getApplication();
String API = application.getAPI();
tinyDB = new TinyDB(context);
mixpanel = MixpanelAPI.getInstance(context, application.getMixpanelId());
final String token = tinyDB.getString(AppConstants.GA_ACCESS_TOKEN);
OkHttpClient okHttpClient = new OkHttpClient();
RequestInterceptor requestInterceptor = new RequestInterceptor() {
#Override
public void intercept(RequestFacade request) {
request.addHeader("Accept", "application/json");
request.addHeader("Authorization", "Token " + token);
}
};
restAdapter = new RestAdapter.Builder()
.setClient(new OkClient(okHttpClient))
.setLogLevel(RestAdapter.LogLevel.FULL)
.setEndpoint(API)
.setRequestInterceptor(requestInterceptor)
.build();
mGoogleApiClient = new GoogleApiClient.Builder(context)
.enableAutoManage((ImageDetailSliderActivity)context, 0 /* clientId */, this)
.addApi(Places.GEO_DATA_API)
.build();
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
LogUtil.i(TAG, "instantiateItem called");
View view = layoutInflater.inflate(R.layout.viewpager_image_detail, container, false);
holder = new ViewHolder(view);
final ImageDetailData item = list.get(position);
imageId = item.getPhotoId();
holder.bar.setVisibility(View.INVISIBLE);
holder.deletePhoto.setVisibility(View.INVISIBLE);
holder.locationIcon.setVisibility(View.GONE);
holder.galleryList.setFocusable(false);
holder.commentList.setFocusable(false);
googlePlaceId = null;
finalPlace = null;
updateNeeded = false;
commentId = null;
imageUrl = null;
final ProgressDialog progressDialog = new ProgressDialog(context);
progressDialog.setMessage("Loading...");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
if (!TextUtils.isEmpty(item.getPhotoUrl())) {
imageUrl = item.getPhotoUrl();
Uri uri = Uri.parse(item.getPhotoUrl());
ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri)
.setProgressiveRenderingEnabled(true)
.build();
DraweeController controller = Fresco.newDraweeControllerBuilder()
.setImageRequest(request)
.setOldController(holder.image.getController())
.build();
holder.image.setController(controller);
}
Picasso.with(context)
.load(tinyDB.getString(AppConstants.USER_DP))
.resize(radius, radius)
.centerCrop()
.transform(new CircleTransform())
.into(holder.userDp);
TextWatcher textWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
Picasso.with(context)
.load(R.drawable.cta_button_post)
.into(holder.postButton);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
if (TextUtils.isEmpty(holder.writeComment.getText().toString().trim())) {
Picasso.with(context)
.load(R.drawable.cta_button_post_in_active)
.into(holder.postButton);
} else {
Picasso.with(context)
.load(R.drawable.cta_button_post)
.into(holder.postButton);
}
}
};
holder.writeComment.addTextChangedListener(textWatcher);
holder.comment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
scrollToComment();
}
});
holder.seeAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, AllGalleriesActivity.class);
intent.putExtra(KEY_SEND_ALL_GALLERY_PHOTO_ID, item.getPhotoId());
context.startActivity(intent);
}
});
//show and hide fab based on whether autocomplete textview has focus or not
holder.autoCompleteTextView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
((ImageDetailSliderActivity)context).hideFab();
} else {
((ImageDetailSliderActivity)context).showFab();
}
}
});
LogUtil.i(TAG, "Id of image = " + item.getPhotoId());
PhotoAPI photoAPI = restAdapter.create(PhotoAPI.class);
photoAPI.getFeed(item.getPhotoId(), new Callback<ImageItem>() {
#Override
public void success(final ImageItem photoDetails, Response response) {
LogUtil.i(TAG, "photo api successful");
DialogUtils.safelyDismissDialog(progressDialog);
holder.locationIcon.setVisibility(View.VISIBLE);
if (TextUtils.isEmpty(item.getPhotoUrl())) {
imageUrl = photoDetails.getPhotoUrl();
item.setPhotoUrl(photoDetails.getPhotoUrl());
Uri uri = Uri.parse(photoDetails.getPhotoUrl());
ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri)
.setProgressiveRenderingEnabled(true)
.build();
DraweeController controller = Fresco.newDraweeControllerBuilder()
.setImageRequest(request)
.setOldController(holder.image.getController())
.build();
holder.image.setController(controller);
}
if (photoDetails.isOwner()) {
holder.buttonBookmark.setVisibility(View.GONE);
holder.bar.setVisibility(View.VISIBLE);
holder.deletePhoto.setVisibility(View.VISIBLE);
holder.separator.setVisibility(View.VISIBLE);
if (TextUtils.isEmpty(photoDetails.getCaption())) {
holder.addCaption.setVisibility(View.VISIBLE);
} else {
holder.updateCaption1.setVisibility(View.VISIBLE);
}
if (TextUtils.isEmpty(photoDetails.getLocation())) {
holder.loc.setVisibility(View.GONE);
showAutoComplete();
} else {
holder.loc.setVisibility(View.VISIBLE);
holder.location.setText(photoDetails.getLocation());
showEditOrRemove();
}
if (photoDetails.getCampaignInfo() != null) {
showCleartripCampaign(photoDetails.getCampaignInfo());
} else {
showAddToExisting();
}
} else {
if (TextUtils.isEmpty(photoDetails.getLocation())) {
holder.loc.setVisibility(View.GONE);
} else {
holder.loc.setVisibility(View.VISIBLE);
holder.location.setText(photoDetails.getLocation());
}
}
if (!TextUtils.isEmpty(photoDetails.getCaption())) {
holder.caption.setText(photoDetails.getCaption());
} else {
holder.caption.setVisibility(View.GONE);
}
holder.time.setText(photoDetails.getTime());
holder.username.setText(photoDetails.getUserName());
holder.userFives.setText(String.format("%s Karma", Integer.toString(photoDetails.getUserKarma())));
holder.numComments.setText(Integer.toString(photoDetails.getNumComments()));
holder.numComments.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, CommentsActivity.class);
intent.putExtra(KEY_SEND_PHOTO_ID, item.getPhotoId());
context.startActivity(intent);
}
});
holder.commentIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, CommentsActivity.class);
intent.putExtra(KEY_SEND_PHOTO_ID, item.getPhotoId());
context.startActivity(intent);
}
});
holder.updateCaption1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
updateCaption();
}
});
holder.addCaption.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateCaption();
}
});
Picasso.with(context)
.load(photoDetails.getProfilePic())
.placeholder(R.drawable.feed_shape_profile_pic)
.resize(radius, radius)
.centerCrop()
.transform(new CircleTransform())
.into(holder.profilePic);
holder.profilePic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, UserProfileActivity.class);
intent.putExtra(KEY_SEND_USER_ID, Integer.toString(photoDetails.getOwnerPk()));
context.startActivity(intent);
}
});
imageGalleryAdapter = new ImageGalleryAdapter(context, photoDetails.getGalleries(), item.getPhotoId());
holder.galleryList.setAdapter(imageGalleryAdapter);
setListViewHeightBasedOnChildren(holder.galleryList);
latestComments = photoDetails.getLatestComments();
imageCommentAdapter = new ImageCommentAdapter(context, latestComments);
holder.commentList.setAdapter(imageCommentAdapter);
setListViewHeightBasedOnChildren(holder.commentList);
if (photoDetails.isBookmarked()) {
Picasso.with(context)
.load(R.drawable.cta_button_bookmark_secondary_state)
.into(holder.buttonBookmark);
} else {
Picasso.with(context)
.load(R.drawable.cta_button_bookmark_default_state)
.into(holder.buttonBookmark);
}
holder.buttonBookmark.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!photoDetails.isBookmarked()) {
Picasso.with(context)
.load(R.drawable.cta_button_bookmark_secondary_state)
.into(holder.buttonBookmark);
photoDetails.setIsBookmarked(true);
BookmarkUserAPI api = restAdapter.create(BookmarkUserAPI.class);
api.post(Integer.toString(photoDetails.getOwnerPk()), new Callback<ActionResponse>() {
#Override
public void success(ActionResponse actionResponse, Response response) {
LogUtil.i(TAG, "bookmark successful");
}
#Override
public void failure(RetrofitError error) {
LogUtil.i(TAG, "bookmark failed");
}
});
} else {
Picasso.with(context)
.load(R.drawable.cta_button_bookmark_default_state)
.into(holder.buttonBookmark);
photoDetails.setIsBookmarked(false);
UnBookmarkUserAPI api = restAdapter.create(UnBookmarkUserAPI.class);
api.post(Integer.toString(photoDetails.getOwnerPk()), new Callback<ActionResponse>() {
#Override
public void success(ActionResponse actionResponse, Response response) {
LogUtil.i(TAG, "unbookmark successful");
}
#Override
public void failure(RetrofitError error) {
LogUtil.i(TAG, "unbookmark failed");
}
});
}
}
});
holder.deletePhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
updateNeeded = true;
FeedFragment.updateDelete(updateNeeded);
GalleryActivity.updateDelete(updateNeeded);
updateNeeded = !updateNeeded;
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog_delete);
dialog.show();
TextView cancel = (TextView) dialog.findViewById(R.id.textView174);
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DialogUtils.safelyDismissDialog(dialog);
}
});
TextView deleteButton = (TextView) dialog.findViewById(R.id.textView175);
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DeletePhotoAPI deletePhotoAPI = restAdapter.create(DeletePhotoAPI.class);
deletePhotoAPI.delete(item.getPhotoId(), new Callback<ActionResponse>() {
#Override
public void success(ActionResponse actionResponse, Response response) {
LogUtil.i(TAG, "image deleted successfully");
Toast.makeText(context.getApplicationContext(), "Image deleted successfully", Toast.LENGTH_SHORT).show();
((ImageDetailSliderActivity) context).finish();
}
#Override
public void failure(RetrofitError error) {
LogUtil.i(TAG, "image could not be deleted");
}
});
}
});
}
});
commentId = Integer.toString(photoDetails.getPk());
holder.postButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
postComment();
}
});
holder.image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, AlternateFullImageActivity.class);
intent.putExtra(KEY_SEND_PHOTO_ID, item.getPhotoId());
intent.putExtra(KEY_SEND_PHOTO_URL, item.getPhotoUrl());
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
context.startActivity(intent);
((ImageDetailSliderActivity)context).overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
});
}
#Override
public void failure(RetrofitError error) {
LogUtil.i(TAG, "photo api failed");
}
});
container.addView(view);
return view;
}
#Override
public int getCount() {
return list == null ? 0 : list.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
LogUtil.i(TAG, "onConnectionFailed called");
}
public static class ViewHolder {
#Bind(R.id.imageView102)
SimpleDraweeView image;
#Bind(R.id.textView38)
TextView caption;
#Bind(R.id.textView39)
TextView time;
#Bind(R.id.textView45)
TextView username;
#Bind(R.id.textView46)
TextView userFives;
#Bind(R.id.imageView107)
ImageView profilePic;
#Bind(R.id.listView2)
ListView galleryList;
#Bind(R.id.textView57)
TextView seeAll;
#Bind(R.id.listView6)
ListView commentList;
#Bind(R.id.editText6)
EditText writeComment;
#Bind(R.id.imageView108)
ImageView buttonBookmark;
#Bind(R.id.imageView233)
ImageView editButton;
#Bind(R.id.textView151)
TextView numComments;
#Bind(R.id.textView82)
TextView bar;
#Bind(R.id.textView83)
TextView deletePhoto;
#Bind(R.id.textView79)
TextView comment;
#Bind(R.id.imageView116)
ImageView userDp;
#Bind(R.id.rel)
RelativeLayout rel;
#Bind(R.id.imageView131)
ImageView postButton;
#Bind(R.id.editText15)
EditText editCaption;
#Bind(R.id.textView184)
TextView separator;
#Bind(R.id.textView185)
TextView updateCaption1;
#Bind(R.id.textView186)
TextView updateCaption2;
#Bind(R.id.loc)
LinearLayout loc;
#Bind(R.id.textView115)
TextView location;
#Bind(R.id.locAuto)
RelativeLayout locAuto;
#Bind(R.id.autoCompleteTextView)
AutoCompleteTextView autoCompleteTextView;
#Bind(R.id.locEdit)
LinearLayout locEdit;
#Bind(R.id.editLocation)
TextView editLocation;
#Bind(R.id.removeLocation)
TextView removeLocation;
#Bind(R.id.scrollView)
ScrollView scrollView;
#Bind(R.id.imageView173)
ImageView locationIcon;
#Bind(R.id.textView5)
TextView addCaption;
#Bind(R.id.imageView11)
ImageView commentIcon;
public ViewHolder(View view) {
ButterKnife.bind(this, view);
}
}
}
just add this method to your Class
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
it will render every time when you enter to particular layout. this is the override method of pagerAdapter.