Actually, I am adding objects in ArrayList from a RecyclerAdapter and I have written a function for getting the arraylist in adapter.And I am getting the arraylist from that function in MainActivity.But whenever I am trying to pass that arraylist from MainActivity to a Fragment it is giving NullPointer(Null value).
Help me.
package com.example.codingmounrtain.addtocartbadgecount.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.codingmounrtain.addtocartbadgecount.activity.MainActivity;
import com.example.codingmounrtain.addtocartbadgecount.ModelClasses.Movie;
import com.example.codingmounrtain.addtocartbadgecount.R;
import com.example.codingmounrtain.addtocartbadgecount.interfaces.AddorRemoveCallbacks;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder> {
ArrayList<Movie> cartmovies = new ArrayList<>();
public interface Listener {
void onSelectMovie(int position);
}
Context context;
private final ArrayList<Movie> movies;
private final Listener listener;
public RecyclerAdapter(Context context, ArrayList<Movie> movies,Listener listener) {
this.context = context;
this.movies = movies;
this.listener = listener;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.row_layout,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
holder.productName.setText(movies.get(position).getTitle());
Picasso.with(context).load(movies.get(position).getPhoto()).centerCrop().resize(400,400).into(holder.productImage);
holder.productImage.setImageResource(movies.get(position).getPhoto());
holder.productImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listener.onSelectMovie(position);
}
});
holder.addRemoveBt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!movies.get(position).isAddedTocart())
{
Log.v("tej","tej");
movies.get(position).setAddedTocart(true);
Log.v("t","t");
holder.addRemoveBt.setText("Remove");
Movie movie = movies.get(position);
cartmovies.add(movie);
Log.v("t","t");
if(context instanceof MainActivity)
{
((AddorRemoveCallbacks)context).onAddProduct();
}
}
else
{
movies.get(position).setAddedTocart(false);
Movie movie = movies.get(position);
cartmovies.remove(movie);
holder.addRemoveBt.setText("Add");
((AddorRemoveCallbacks)context).onRemoveProduct();
}
}
});
}
public ArrayList<Movie> getArrayList(){
return cartmovies;
}
#Override
public int getItemCount() {
return movies.size();
}
class MyViewHolder extends RecyclerView.ViewHolder{
ImageView productImage;
TextView productName;
Button addRemoveBt;
public MyViewHolder(View itemView) {
super(itemView);
productImage=(ImageView) itemView.findViewById(R.id.productImageView);
productName=(TextView) itemView.findViewById(R.id.productNameTv);
addRemoveBt=(Button)itemView.findViewById(R.id.addButton);
}
}
}
MainActivity.java
package com.example.codingmounrtain.addtocartbadgecount.activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.example.codingmounrtain.addtocartbadgecount.Converter;
import com.example.codingmounrtain.addtocartbadgecount.ModelClasses.Movie;
import com.example.codingmounrtain.addtocartbadgecount.R;
import com.example.codingmounrtain.addtocartbadgecount.adapter.RecyclerAdapter;
import com.example.codingmounrtain.addtocartbadgecount.fragment.CartFragment;
import com.example.codingmounrtain.addtocartbadgecount.fragment.SearchFragment;
import com.example.codingmounrtain.addtocartbadgecount.interfaces.AddorRemoveCallbacks;
import java.util.ArrayList;
import java.util.Iterator;
public class MainActivity extends AppCompatActivity implements AddorRemoveCallbacks,RecyclerAdapter.Listener{
ArrayList<Movie> cartmovies = new ArrayList<>();
ArrayList<Movie> movies = new ArrayList<>();
RecyclerView mRecyclerView;
RecyclerAdapter mAdapter;
private static int cart_count=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("MovieShop");
getSupportActionBar().show();
movies.add(new Movie("Stree","A town is held in the grip of terror by tales of a mysterious woman who calls men by their name and then abducts them, leaving their clothes behind.","Rajkummar Rao","Shraddha Kapoor","Amar Kaushik",4.0f,R.drawable.stree));
movies.add(new Movie("Nun","When a young nun at a cloistered abbey in Romania takes her own life, a priest with a haunted past and a novitiate on the threshold of her final vows are sent by the Vatican to investigate. ","Demián Bichir","Taissa Farmiga","Corin Hardy",2.5f,R.drawable.nun));
movies.add(new Movie("Savita Damodar Paranjpe","The lives of a married couple are turned upside down when hard truths come to light.","Subodh Bhave","Trupti Madhukar Toradmal","Swapna Waghmare Joshi",3.5f,R.drawable.savita));
movies.add(new Movie("TC GN"," A recently retired professional is cheated of a large sum of money through a digital fraud. ","Sachin Khedekar","Iravati Harshe","Girish Jayant Joshi",3.0f,R.drawable.tcgn));
movies.add(new Movie("MI","Ethan Hunt and the IMF team join forces with CIA assassin August Walker to prevent a disaster of epic proportions.","Tom Cruise","Rebecca Ferguson","Christopher McQuarrie",4.0f,R.drawable.mi));
movies.add(new Movie("Searching","After David Kim (John Cho)'s 16-year-old daughter goes missing, a local investigation is opened and a detective is assigned to the case. ","John Cho","Debra Messing","Aneesh Chaganty",2.5f,R.drawable.searching));
movies.add(new Movie("SURYA"," Indian Telugu-language action film written and directed by Vakkantham Vamsi in his directorial debut. ","Allu Arjun","Anu Emmanuel","Vakkantham Vamsi",3.5f,R.drawable.surya));
movies.add(new Movie("TC GN"," A recently retired professional is cheated of a large sum of money through a digital fraud. ","Sachin Khedekar","Iravati Harshe","Girish Jayant Joshi",3.0f,R.drawable.tcgn));
mRecyclerView = findViewById(R.id.recyclerview);
mRecyclerView.setHasFixedSize(true);
GridLayoutManager mLayoutManager = new GridLayoutManager(this,2);
mRecyclerView.setLayoutManager(mLayoutManager);
// specify an adapter (see also next example)
mAdapter = new RecyclerAdapter(this, movies,this);
mRecyclerView.setAdapter(mAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem menuItem = menu.findItem(R.id.cart_action);
menuItem.setIcon(Converter.convertLayoutToImage(MainActivity.this,cart_count,R.drawable.ic_shopping_cart_white_24dp));
MenuItem menuItem2 = menu.findItem(R.id.search_action);
menuItem2.setIcon(R.drawable.ic_search_black_24dp);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
cartmovies = mAdapter.getArrayList();
Movie movie = null;
Iterator<Movie> iter = cartmovies.iterator();
while ( iter .hasNext() == true )
{
movie = iter.next();
Log.v("tejjjj",movie.getTitle());
}
// cartmovies.get(0).getTitle();
if(id==R.id.cart_action){
Bundle bundle = new Bundle();
bundle.putSerializable("catmovies",cartmovies);
Fragment fragment = new CartFragment();
fragment.setArguments(bundle);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.contentLayout, fragment)
.addToBackStack("MainActivity")
.commit();
}
if(id==R.id.search_action){
Bundle bundle = new Bundle();
// bundle.putString("query", editSearch.getText().toString());
bundle.putSerializable("movies",movies);
Fragment fragment = new SearchFragment();
fragment.setArguments(bundle);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.contentLayout, fragment)
.addToBackStack("MainActivity")
.commit();
// search(searchStr, movies);
}
return super.onOptionsItemSelected(item);
}
#Override
public void onAddProduct() {
cart_count++;
Log.v("stej",""+cart_count);
invalidateOptionsMenu();
Snackbar.make((CoordinatorLayout)findViewById(R.id.parentlayout), "Movie added to cart !!", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
#Override
public void onRemoveProduct() {
cart_count--;
Log.v("tej",""+cart_count);
invalidateOptionsMenu();
Snackbar.make((CoordinatorLayout)findViewById(R.id.parentlayout), "Movie removed from cart !!", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
#Override
public void onSelectMovie(int position) {
Movie movie = movies.get(position);
// Toast.makeText(this, "selected movie: " + movie.getTitle(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(this, DetailActivity.class);
intent.putExtra("title",movie.getTitle());
intent.putExtra("director",movie.getDirector());
intent.putExtra("actors",movie.getActors());
intent.putExtra("actresses",movie.getActresses());
intent.putExtra("info",movie.getDescription());
intent.putExtra("photo",movie.getPhoto());
intent.putExtra("rating",movie.getRating());
startActivity(intent);
}
}
CartFragment.java
package com.example.codingmounrtain.addtocartbadgecount.fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import com.example.codingmounrtain.addtocartbadgecount.ModelClasses.Movie;
import com.example.codingmounrtain.addtocartbadgecount.R;
import com.example.codingmounrtain.addtocartbadgecount.activity.DetailActivity;
import com.example.codingmounrtain.addtocartbadgecount.adapter.MovieListAdapter;
import com.example.codingmounrtain.addtocartbadgecount.adapter.RecyclerAdapter;
import java.util.ArrayList;
import java.util.Iterator;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
public class CartFragment extends Fragment implements View.OnClickListener, MovieListAdapter.Listener {
#BindView(R.id.recyclerView)
RecyclerView recyclerView;
Unbinder unbinder;
MovieListAdapter adapter;
RecyclerAdapter madapter;
ArrayList<Movie> movies = new ArrayList<>();
ArrayList<Movie> movies1 = new ArrayList<>();
public CartFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.fragment_cart, null);
unbinder = ButterKnife.bind(this, layout);
adapter = new MovieListAdapter(getActivity(),movies,this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 1));
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("Movie Cart");
// movies1 =(ArrayList<Movie>) savedInstanceState.getParcelable("movies");
// buttonSearch.setOnClickListener(this);
return layout;
}
#Override
public void onResume() {
super.onResume();
getList();
}
#Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
}
void getList(){
Bundle bundle = getArguments();
movies1 =(ArrayList<Movie>) bundle.getSerializable("cartmovies");
Iterator<Movie> iter = movies1.iterator();
Movie movie = null;
while(iter.hasNext() == true){
movie = iter.next();
movies.add(movie);
adapter.notifyDataSetChanged();
}
}
#Override
public void onClick(View view) {
}
#Override
public void onSelectMovie(int position) {
Movie movie = movies.get(position);
Intent intent = new Intent(getActivity(),DetailActivity.class);
intent.putExtra("title",movie.getTitle());
intent.putExtra("director",movie.getDirector());
intent.putExtra("actors",movie.getActors());
intent.putExtra("actresses",movie.getActresses());
intent.putExtra("info",movie.getDescription());
intent.putExtra("photo",movie.getPhoto());
intent.putExtra("rating",movie.getRating());
startActivity(intent);
}
}
Write a get method inside your adapter then call it from your activity or fragment.
public ArrayList<Object> getArrayList() {
return yourArrayList;
}
Inside your activity you can get this like, yourAdapterObject.getArrayList();
Try to pass it via bundle.
First create a model class which will be passed. It should implement Serializable
public class MyModel implements Serializable {
private ArrayList<Data> datas;
public MyModel(ArrayList<Data> datas) {
this.datas = datas
}
}
Then put your data to the bundle
Bundle bundle = new Bundle();
bundle.putSerializable();
Finally put that bundle instance to your fragment
myFragment.setArguments(bundle);
You can pass your array list to fragment by setting arguments for that fragment. But for that, the type of object your array list contains should extend Serializable. Then make a getInstance() method in your fragment that returns an instance of your fragment and wherever you are opening your fragment call that getInstance() method and pass your Array list.
getSupportFragmentManager().beginTransaction()
.add(containerId, YourFragment.getInstance(yourArrayList), tag)
.commitAllowingStateLoss();
The sample code snippet for getInstance() method in your fragment is:
public static YourFragment getInstance( ArrayList<Object> yourArrayList) {
Bundle bundle = new Bundle();
bundle.putParcelableArrayList(Constants.YOUR_LIST,yourArrayList);
YourFragment yourFragment = new YourFragment();
yourFragment.setArguments(bundle);
return yourFragment;
}
Now, you can get your arraylist by calling getArguments() wherever need in your fragment. Also, make sure to check for null Arguments. The sample code for this is:
if (getArguments()!=null && getArguments().containsKey(Constants.YOUR_LIST) && getArguments().getParcelableArrayList(Constants.YOUR_LIST) != null){
ArrayList<Object> yourlist = getArguments().getParcelableArrayList(Constants.YOUR_LIST);
}
Now, by making this list global you can access it anywhere in the fragment. Hope, it helps.
Related
I have been trying to create a ListView with the PlaylistsAdapter. But whenever I try to click on imgCoverArt, the app crashes, stating that the songlist has a size of 0. I have tried changing the types of the variables and just changing the codes overall. But I just couldn't fix it and I don't know the issue.
Thanks in advance.
This was the error I got:
2020-08-10 03:52:56.720 3091-3091/sg.edu.tp.musicstream E/AndroidRuntime: FATAL EXCEPTION: main
Process: sg.edu.tp.musicstream, PID: 3091
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:437)
at sg.edu.tp.musicstream.PlaylistsAdapter$1.onClick(PlaylistsAdapter.java:88)
at android.view.View.performClick(View.java:6294)
at android.view.View$PerformClick.run(View.java:24770)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
I have tried to include the relevant classes and please let me know if you need anything else.
package sg.edu.tp.musicstream;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.TextView;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import sg.edu.tp.musicstream.util.AppUtil;
public class PlaylistsAdapter extends BaseAdapter {
Context mContext;
LayoutInflater inflater;
Song[] songs;
List<Song> songlist;
ArrayList<Song> arrayList;
public PlaylistsAdapter(Context context, List<Song> songlist, Song[] songs)
{
mContext = context;
inflater = LayoutInflater.from(mContext);
this.songs = songs;
this.songlist = songlist;
this.arrayList = new ArrayList<>();
this.arrayList.addAll(songlist);
}
public class ViewHolder
{
ImageButton imgCoverArt;
TextView txtSongTitle;
TextView txtArtist;
ImageButton btnAddToPlaylist;
}
#Override
public int getCount() {
return songlist.size();
}
#Override
public Object getItem(int position) {
return songlist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.playlist_listview, null);
holder.imgCoverArt = convertView.findViewById(R.id.imgCoverArt);
holder.txtSongTitle = convertView.findViewById(R.id.txtSongTitle);
holder.txtArtist = convertView.findViewById(R.id.txtArtist);
holder.btnAddToPlaylist = convertView.findViewById(R.id.btnAddToPlaylist);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.imgCoverArt.setImageResource(songlist.get(position).getCoverArt());
holder.imgCoverArt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int index = 0; index < songs.length; index++)
{
if (songlist.get(position).getId().equals(songs[index].getId())) {
Song song = songs[index];
sendDataToActivity(songs, song);
AppUtil.popMessage(mContext, ""+ songlist.size());
}
}
}
});
holder.txtSongTitle.setText(songlist.get(position).getTitle());
holder.txtArtist.setText(songlist.get(position).getArtist());
if (position >= 10) {
holder.btnAddToPlaylist.setContentDescription("S10" + position);
} else {
holder.btnAddToPlaylist.setContentDescription("S100" + position);
}
return convertView;
}
public void sendDataToActivity(Song[] songs, Song song)
{
// 1. Create a new Intent and specify the source and destination screen/activity.
Intent intent = new Intent(mContext, PlaySongActivity.class);
songlist = HomeFragment.arrayList;
songlist = new ArrayList<>();
// 2. Store the song information into the Intent object to be sent over to the destination screen.
intent.putExtra("id", song.getId());
intent.putExtra("title", song.getTitle());
intent.putExtra("artist", song.getArtist());
intent.putExtra("fileLink", song.getFileLink());
intent.putExtra("coverArt", song.getCoverArt());
intent.putExtra("songs", songs);
intent.putExtra("songlist", (Serializable) songlist);
// 3. Launch the destination screen/activity
mContext.startActivity(intent);
}
public void filter(String charText){
charText = charText.toLowerCase(Locale.getDefault());
songlist.clear();
if (charText.length()==0){
songlist.addAll(arrayList);
}
else {
for (Song song : arrayList){
if (song.getTitle().toLowerCase(Locale.getDefault())
.contains(charText) || song.getArtist().toLowerCase(Locale.getDefault())
.contains(charText)){
songlist.add(song);
}
}
}
notifyDataSetChanged();
}
package sg.edu.tp.musicstream;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.SearchView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import com.google.android.material.tabs.TabLayout;
import java.util.ArrayList;
import sg.edu.tp.musicstream.ui.main.SectionsPagerAdapter;
import sg.edu.tp.musicstream.util.AppUtil;
public class HomeActivity extends AppCompatActivity {
private SectionsPagerAdapter sectionsPagerAdapter;
private SongCollection songCollection = new SongCollection();
static Song[] playlistSongs = new Song[14];
static ArrayList<Song> playlist = new ArrayList<>();
private Fragment homeFragment;
private Fragment playlistsFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
homeFragment = new HomeFragment();
playlistsFragment = new PlaylistsFragment();
sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
ViewPager viewPager = findViewById(R.id.view_pager);
setUpViewPager(viewPager);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
}
private void setUpViewPager(ViewPager viewPager) {
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
sectionsPagerAdapter.addFragment(homeFragment, "Recommended Songs");
sectionsPagerAdapter.addFragment(playlistsFragment, "Playlist");
viewPager.setAdapter(sectionsPagerAdapter);
}
public void addToPlaylist (View view) {
String songId = view.getContentDescription().toString();
Song song = songCollection.searchById(SongCollection.recommendedSongs, songId);
playlist.add(song);
AppUtil.popMessage(this, "Added " + song.getTitle() + " to playlist!");
playlistSongs[playlist.size()] = song;
sectionsPagerAdapter.removeFragment(playlistsFragment, "Playlist");
sectionsPagerAdapter.addFragment(new PlaylistsFragment(), "Playlist");
ViewPager viewPager = findViewById(R.id.view_pager);
setUpViewPager(viewPager);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
}
public void removeAll(View view) {
playlist.clear();
PlaylistsFragment.songAdapter.notifyDataSetChanged();
}
}
package sg.edu.tp.musicstream;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.text.TextUtils;
import android.view.MenuItem;
import java.util.ArrayList;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.SearchView;
import androidx.fragment.app.Fragment;
public class HomeFragment extends Fragment {
private PlaylistsAdapter playlistsAdapter;
private ListView listView;
static ArrayList<Song> arrayList = new ArrayList<>();
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container,false);
for (int index =0; index<SongCollection.recommendedSongs.length; index++) {
arrayList.add(SongCollection.recommendedSongs[index]);
}
listView = view.findViewById(R.id.listView);
playlistsAdapter = new PlaylistsAdapter(getActivity(), arrayList, SongCollection.recommendedSongs);
listView.setAdapter(playlistsAdapter);
setHasOptionsMenu(true);
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu, menu);
MenuItem myActionMenuItem = menu.findItem(R.id.search);
SearchView searchView = (SearchView)myActionMenuItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
if (TextUtils.isEmpty(s)){
playlistsAdapter.filter("");
listView.clearTextFilter();
}
else {
playlistsAdapter.filter(s);
}
return true;
}
});
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id==R.id.settings){
Intent intent = new Intent(getActivity(), LoginActivity.class);
startActivity(intent);
return true;
}
if (id==R.id.logOut){
Intent intent = new Intent(getActivity(), LoginActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
package sg.edu.tp.musicstream;
import java.util.List;
import java.util.Random;
public class SongCollection
{
static Song[] recommendedSongs = new Song[14];
private Song[] playlist1 = new Song[5];
private Song[] playlist2 = new Song[5];
public SongCollection()
{
//Recommended Songs
Song photograph = new Song("S1000", "Photograph", "Ed Sheeran","097c7b735ceb410943cbd507a6e1dfda272fd8a8?cid=null",4.32, R.drawable.photograph);
Song theWayYouLookTonight = new Song("S1001", "The Way You Look Tonight", "Michael Buble","a5b8972e764025020625bbf9c1c2bbb06e394a60?cid=null",4.39,R.drawable.michael_buble_collection);
Song billieJean = new Song("S1002", "Billie Jean", "Michael Jackson","f504e6b8e037771318656394f532dede4f9bcaea?cid=2afe87a64b0042dabf51f37318616965",4.39,R.drawable.billie_jean);
Song spark = new Song("S1003", "Spark", "TAEYEON","e857ae54599f2cca1703b598cef871664f36e72e?cid=2afe87a64b0042dabf51f37318616965", 3.63, R.drawable.spark);
Song darkside = new Song("S1004", "Darkside", "Alan Walker","2acc534ac733f8868c98e13e4f71917fae2e3ce3?cid=2afe87a64b0042dabf51f37318616965", 3.53, R.drawable.darkside);
Song diamondHeart = new Song("S1005", "Diamond Heart", "Alan Walker","d75c2b8e870acb087872bd49eeb5d6efb37cfc9d?cid=2afe87a64b0042dabf51f37318616965", 4.01, R.drawable.diamond_heart);
Song ocean= new Song("S1006", "Ocean (feat. Khalid)", "Martin Garrix","5ce5ed5600e96f1604aff6b05c0dc35319023a1c?cid=2afe87a64b0042dabf51f37318616965", 3.61, R.drawable.ocean);
Song numb = new Song("S1007", "Numb", "Linkin Park","e6ccf7717f8a167bfea4afc1bf7da1a0cd707fbb?cid=2afe87a64b0042dabf51f37318616965", 3.09, R.drawable.numb);
Song sadForever = new Song("S1008", "Sad Forever", "Lauv","1250fb3bea03aee6da908ea67420ddd954ad812a?cid=2afe87a64b0042dabf51f37318616965", 3.39, R.drawable.sad_forever);
Song kyokiranbu = new Song("S1009", "Kyokiranbu", "GARNiDELiA","ec373ab20f18e1a4a7b19b3abaac3ce605690abd?cid=2afe87a64b0042dabf51f37318616965", 4.32, R.drawable.kyokiranbu);
Song gokurakuJoudo= new Song("S1010", "Gokuraku Joudo", "GARNiDELiA","8924599ac778ebfbac7ddc2e5cc87961f82f736c?cid=2afe87a64b0042dabf51f37318616965", 3.65, R.drawable.gokuraku_joudo);
Song connect = new Song("S1011", "Connect", "ClariS","6692db454109aa077ed25e65df82a06d34017da6?cid=2afe87a64b0042dabf51f37318616965", 4.5, R.drawable.connect);
Song wannabe = new Song("S1012", "WANNABE", "ITZY", "2bae7f42bbae3cd75228d6400e37515b79467928?cid=2afe87a64b0042dabf51f37318616965", 3.19, R.drawable.wannabe);
Song icy = new Song("S1013", "ICY", "ITZY", "118a0dea24f229f51ffff23a9d334cf5714dbaf6?cid=2afe87a64b0042dabf51f37318616965", 3.19, R.drawable.icy);
recommendedSongs[0] = photograph;
recommendedSongs[1] = theWayYouLookTonight;
recommendedSongs[2] = billieJean;
recommendedSongs[3] = spark;
recommendedSongs[4] = darkside;
recommendedSongs[5] = diamondHeart;
recommendedSongs[6] = ocean;
recommendedSongs[7] = numb;
recommendedSongs[8] = sadForever;
recommendedSongs[9] = kyokiranbu;
recommendedSongs[10] = gokurakuJoudo;
recommendedSongs[11] = connect;
recommendedSongs[12] = wannabe;
recommendedSongs[13] = icy;
}
In your adapter, you have three different ways of storing the songs:
Song[] songs;
List<Song> songlist;
ArrayList<Song> arrayList;
This is a problem. Pick one type, and use it everywhere.
The adapter is building its logic around the getCount() method:
#Override
public int getCount() {
return songlist.size();
}
Which uses songlist. But your onClick() method uses songs:
#Override
public void onClick(View v) {
for (int index = 0; index < songs.length; index++)
// ...
}
If you change this to use songlist instead, probably the issue will go away.
The title says it all. I am attempting to send an ArrayList that has data inside from one fragment to another and then switch and show the second fragment (the one that just received the ArrayList).
here is my MainActivity.java:
package;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import android.view.View;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.google.android.material.navigation.NavigationView;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.Menu;
public class MainActivity extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
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();
}
});
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_display)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration) || super.onSupportNavigateUp();
}
}
here is my HomeFragment.java (the sending fragment):
package;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.navigation.Navigation;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.ml.vision.FirebaseVision;
import com.google.firebase.ml.vision.common.FirebaseVisionImage;
import com.google.firebase.ml.vision.text.FirebaseVisionText;
import com.google.firebase.ml.vision.text.FirebaseVisionTextDetector;
import com.mvsolutions.snap.R;
import com.mvsolutions.snap.ui.display.DisplayFragment;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.Inflater;
import static android.app.Activity.RESULT_OK;
public class HomeFragment extends Fragment {
private HomeViewModel homeViewModel;
private ImageView imageView;
private Button captureImageButton, detectButton, pickButton;
private Bitmap imageBitmap;
private TextView capturedTextView;
static final int REQUEST_IMAGE_CAPTURE = 1;
private static final int RESULT_LOAD_IMAGE = 101;
public View onCreateView(#NonNull final LayoutInflater inflater,
final ViewGroup container, Bundle savedInstanceState) {
//View view = inflater.inflate(R.layout.fragment_home, container, false);
View root = inflater.inflate(R.layout.fragment_home, container, false);
detectButton = root.findViewById(R.id.action_homeFragment_to_displayFragment2);
//detectButton.setOnClickListener((View.OnClickListener) this);
//return view;
homeViewModel = ViewModelProviders.of(this).get(HomeViewModel.class);
//View v = inflater.inflate(R.layout.fragment_display, container, false);
imageView = root.findViewById(R.id.home_image_view_img);
capturedTextView = root.findViewById(R.id.home_text_view_txt);
captureImageButton = root.findViewById(R.id.capture_image_btn);
detectButton = root.findViewById(R.id.detect_text_btn);
//pickButton = root.findViewById(R.id.pick_image_btn);
captureImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
captureImage();
}
});
// pickButton.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// pickImage();
// }
// });
detectButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Navigation.findNavController(v).navigate(R.id.action_homeFragment_to_displayFragment2);
// DisplayFragment displayFragment = new DisplayFragment();
// FragmentManager fragmentManager = getFragmentManager();
// fragmentManager.beginTransaction()
// .replace(R.id.DisplayFragment, displayFragment, displayFragment.getTag())
// .commit();
//detectTextFromImage();
}
});
return root;
}
private void detectTextFromImage() {
capturedTextView.setText("");
FirebaseVisionImage firebaseVisionImage = FirebaseVisionImage.fromBitmap(imageBitmap);
FirebaseVisionTextDetector visionTextDetector = FirebaseVision.getInstance().getVisionTextDetector();
visionTextDetector.detectInImage(firebaseVisionImage).addOnSuccessListener(new OnSuccessListener<FirebaseVisionText>() {
#Override
public void onSuccess(FirebaseVisionText firebaseVisionText) {
List<FirebaseVisionText.Block> textBlocks = firebaseVisionText.getBlocks();
if (textBlocks.size() == 0) {
Toast.makeText(getContext(), "No Text Found", Toast.LENGTH_SHORT).show();
} else {
for (FirebaseVisionText.Block block : textBlocks) {
String text = block.getText();
ArrayList textBlobs = new ArrayList();
textBlobs.add(text);
for(int i = 0; i < textBlobs.size(); i++) {
capturedTextView.setText(capturedTextView.getText() + ", " + textBlobs.get(i));
}
// capturedTextView.setText(capturedTextView.getText() + " " + text);
}
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getContext(), "Something went wrong", Toast.LENGTH_SHORT).show();
Log.d("Error", e.getMessage());
}
});
}
private void pickImage() {
Intent i = new Intent(
Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
private void captureImage() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
imageBitmap = (Bitmap) extras.get("data");
imageView.setImageBitmap(imageBitmap);
}
// else if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
// Uri imageUri = data.getData();
// imageBitmap = MediaStore.Images.Media.decodeBitmap(this.);
// imageView.setImageBitmap(imageBitmap);
// }
}
}
here is my DisplayFragment.java (the receiving fragment):
package com.mvsolutions.snap.ui.display;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import com.mvsolutions.snap.R;
public class DisplayFragment extends Fragment {
private DisplayViewModel DisplayViewModel;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
DisplayViewModel =
ViewModelProviders.of(this).get(DisplayViewModel.class);
View root = inflater.inflate(R.layout.fragment_display, container, false);
// final TextView textView = root.findViewById(R.id.text_gallery);
DisplayViewModel.getText().observe(this, new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
}
});
return root;
}
}
I am currently using a navigation fragment xml file to make the button switch from the first fragment to the second, but I want it to send the data to the second fragment as well.
My two questions are:
Is it possible to both send the data to the second fragment and switch to the second fragment with one button press? or do I have to split it into two?
How do I send the data from the first fragment to the second?
You are using ViewModel so I think the easiest way is to use the same ViewModel for both fragments. In android docs, You can find an example Share data between fragments
It's very common that two or more fragments in an activity need to communicate with each other. Imagine a common case of split-view (master-detail) fragments, where you have a fragment in which the user selects an item from a list and another fragment that displays the contents of the selected item.
public class SharedViewModel extends ViewModel {
private final MutableLiveData<Item> selected = new MutableLiveData<Item>();
public void select(Item item) {
selected.setValue(item);
}
public LiveData<Item> getSelected() {
return selected;
}
}
public class MasterFragment extends Fragment {
private SharedViewModel model;
public void onViewCreated(#NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
model = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
itemSelector.setOnClickListener(item -> {
model.select(item);
});
}
}
public class DetailFragment extends Fragment {
public void onViewCreated(#NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
SharedViewModel model = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
model.getSelected().observe(getViewLifecycleOwner(), { item ->
// Update the UI.
});
}
}
Notice that both fragments retrieve the activity that contains them. That way, when the fragments each get the ViewModelProvider, they receive the same SharedViewModel instance, which is scoped to this activity.
I am making note taking app.i have two fragments in my app first fragment A (ListFragment) contains the recycler adapter .
while when I press adding floating button first fragment A (ListFragment) is replaced with next fragment B(AddingFragment) in which I type new data and then again press adding floating button on fragment B(AddingFragment) to add that new data in data set and then press backfloating button on my fragment B to move back to Fragment A(with recycler adapter) .
This new data item is added to data list every time but never becomes visible in recycler adapter in Fragment A.
package com.example.anonymous.note_taking_app;
import android.app.ActionBar;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
public class AddingFragment extends Fragment {
public AddingFragment()
{
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_adding, container, false);
return view;
}
#Override
public void onResume()
{
super.onResume();
FloatingActionButton floating = (FloatingActionButton) getActivity().findViewById(R.id.addingfloatingbutton);
floating.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Log.i("floating_button", "floating button 2 clicked");
EditText title = (EditText) getActivity().findViewById(R.id.firsttextview);
EditText detial = (EditText) getActivity().findViewById(R.id.secondtextview);
DatabaseHelper db = new DatabaseHelper(getActivity().getApplication());
boolean insert = db.insert(title.getText()+"",detial.getText()+"");
if(insert==true)
{
com.example.anonymous.note_taking_app.ListAdapter l = new com.example.anonymous.note_taking_app.ListAdapter();
ListFragment.it.add(new ListItem(title.getText()+"",detial.getText()+""));
l.notifyItemInserted(ListFragment.it.size()-1);//DataSetChanged();
l.notifyDataSetChanged();
for(int i=0;i<ListFragment.it.size();i++)
{
Log.i("List item"+i+"", ListFragment.it.get(i).getNoteTitle());
}
Log.i("insertion", "is added");
}
else
{
Log.i("insertion", "is not added");
}
}
});
FloatingActionButton floatings = (FloatingActionButton) getActivity().findViewById(R.id.addcancelfloatingbutton);
floatings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
final FragmentManager fragmentManager = getFragmentManager();
fragmentManager.popBackStackImmediate();
}
});
}
}
//
package com.example.anonymous.note_taking_app;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Fragment;
import java.util.ArrayList;
/**
* Created by Anonymous on 12/13/2017.
*/
public class ListAdapter extends RecyclerView.Adapter<ListAdapter.holderclas> implements EditDilogue.EditDilougeinterface
{
static ArrayList<ListItem> i;
Context context;
View view;
ImageButton share;
ImageButton edit;
static int lastposition;
android.app.FragmentManager fm;
public ListAdapter(ArrayList<ListItem> i,android.app.FragmentManager fm)
{
this.i=i;
this.fm=fm;
}
public ListAdapter()
{
}
#Override
public ListAdapter.holderclas onCreateViewHolder(ViewGroup parent, int viewType)
{
view= LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item,parent,false);
holderclas h = new holderclas(view);
share = (ImageButton) view.findViewById(R.id.share);
edit = (ImageButton) view.findViewById(R.id.edit);
return h;
}
#Override
public void onBindViewHolder(ListAdapter.holderclas holder, final int position)
{
final int y= position;
lastposition = position;
final ListItem it = i.get(position);
holder.title.setText(it.getNoteTitle());
holder.details.setText(it.getNoteDetail());
ImageButton b =(ImageButton) view.findViewById(R.id.delete);
b.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Log.i("size", i.size()+"");
i.remove(y);
notifyDataSetChanged();
}
});
share.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Log.i("share", "share");
}
});
edit.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Log.i("edit", i.size()+"edit");
EditDilogue ed = new EditDilogue();
Bundle args = new Bundle();
args.putString("title", it.getNoteTitle());
args.putString("detail", it.getNoteDetail());
ed.setArguments(args);
ed.setTargetFragment(new ListFragment(),1);
ed.show(fm,"fragment");
}
});
}
#Override
public int getItemCount()
{
return i.size();
}
#Override
public void deleteandadd(String titlestring, String detailstring)
{
String oldtitle = i.get(lastposition).getNoteTitle();
String olddetail = i.get(lastposition).getNoteDetail();
Log.i("string", titlestring);
Log.i("string", detailstring);
}
public class holderclas extends RecyclerView.ViewHolder
{
TextView title;
TextView details;
public holderclas(View itemView)
{
super(itemView);
title=(TextView) itemView.findViewById(R.id.title);
details=(TextView) itemView.findViewById(R.id.detail);
}
}
}
//
package com.example.anonymous.note_taking_app;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListAdapter;
import java.util.ArrayList;
/**
* Created by Anonymous on 12/13/2017.
*/
public class ListFragment extends Fragment implements EditDilogue.EditDilougeinterface
{
RecyclerView recyClerView;
RecyclerView.Adapter adapter;
RecyclerView.LayoutManager layoutManager;
public static ArrayList<ListItem> it;
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState)
{
it = new ArrayList<>();
View view = inflater.inflate(R.layout.fragment_list, parent, false);
FloatingActionButton floating = (FloatingActionButton) view.findViewById(R.id.listfloatingbutton);
floating.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
Fragment frg = new AddingFragment();
FragmentManager manager = getFragmentManager();
FragmentTransaction trans = manager.beginTransaction();
trans.replace(R.id.placeholder,frg);
trans.addToBackStack("addingfragment");
trans.commit();
AddingFragment()).addToBackStack("addingfragment").commit();
}
});
for(int i=0;i<5;i++)
{
ListItem t = new ListItem("Time Bank",
"Bank should contain atleast $2000 rupees then i will leave this matter") ;
it.add(t);
}
recyClerView=(RecyclerView) view.findViewById(R.id.recycle);
FragmentManager fm = getFragmentManager();
com.example.anonymous.note_taking_app.ListAdapter l = new com.example.anonymous.note_taking_app.ListAdapter(it,fm);
recyClerView.setAdapter(l);
layoutManager = new LinearLayoutManager(getActivity());
recyClerView.setLayoutManager(layoutManager);
return view;
}
#Override
public void onResume()
{
super.onResume();
if(adapter!=null)
{
adapter.notifyDataSetChanged();
adapter.notifyItemInserted(ListFragment.it.size()-1);
}
}
#Override
public void deleteandadd(String titlestring, String detailstring)
{
String oldtitle = com.example.anonymous.note_taking_app.ListAdapter.i.get(com.example.anonymous.note_taking_app.ListAdapter.lastposition).getNoteTitle();
String olddetail = com.example.anonymous.note_taking_app.ListAdapter.i.get(com.example.anonymous.note_taking_app.ListAdapter.lastposition).getNoteDetail();
Log.i("string", titlestring);
Log.i("string", detailstring);
}
}
I have a custom viewPagerAdapter in this activity, when the first launch of the activity (When the main activity starts it with the intent) the pager displays the fragments correctly, but when I rotate the device, the recipe is got from the savedInstantState, and the adapter is started, but the fragments are not displayed and the getItem method doesn't get callled!
Here's the code for the Activity:
package com.ameer.bake.activities;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.NavUtils;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.ViewGroup;
import com.ameer.bake.Constants;
import com.ameer.bake.fragments.IngredientsFragment;
import com.ameer.bake.fragments.StepDetailsFragment;
import com.ameer.bake.fragments.StepsFragment;
import com.ameer.bake.R;
import com.ameer.bake.models.Recipe;
import com.ameer.bake.models.Step;
import com.google.gson.Gson;
import com.ogaclejapan.smarttablayout.SmartTabLayout;
public class DetailsActivity extends AppCompatActivity implements StepsFragment.StepCallback{
private Recipe recipe;
private IngredientsFragment ingredientsFragment;
private StepsFragment stepsFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if (savedInstanceState != null){
recipe = new Gson().fromJson(savedInstanceState.getString(Constants.RECIPE), Recipe.class);
setupViewPager();
} else if (getIntent().hasExtra(Constants.CURRENT_RECIPE_KEY) ) {
Gson gson = new Gson();
recipe = gson.fromJson(getIntent().getStringExtra(Constants.CURRENT_RECIPE_KEY), Recipe.class);
setTitle(recipe.getName());
setupViewPager();
}
}
#Override
public void onStepClicked(Step step) {
Intent intent = new Intent(DetailsActivity.this, StepActivity.class);
intent.putExtra(Constants.STEP_KEY, new Gson().toJson(step));
startActivity(intent);
}
private class RecipePagerAdapter extends FragmentPagerAdapter {
private static final int NUM_ITEMS = 2;
private final String[] titles = new String[]{
getString(R.string.ingredients), getString(R.string.steps)};
private RecipePagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
if (ingredientsFragment == null && stepsFragment == null) {
ingredientsFragment = new IngredientsFragment();
ingredientsFragment.setIngredients(recipe.getIngredients());
stepsFragment = new StepsFragment();
stepsFragment.setSteps(recipe.getSteps());
stepsFragment.setCallback(DetailsActivity.this);
}
}
// Returns total number of pages
#Override
public int getCount() {
return NUM_ITEMS;
}
// Returns the fragment to display for that page
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return ingredientsFragment;
case 1:
return stepsFragment;
default:
return null;
}
}
// Returns the page title for the top indicator
#Override
public CharSequence getPageTitle(int position) {
return titles[position];
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home){
NavUtils.navigateUpFromSameTask(this);
}
return super.onOptionsItemSelected(item);
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putString(Constants.RECIPE, new Gson().toJson(recipe));
super.onSaveInstanceState(savedInstanceState);
}
private void setupViewPager(){
ViewPager vpPager = (ViewPager) findViewById(R.id.vpPager);
FragmentPagerAdapter pagerAdapter = new RecipePagerAdapter(getSupportFragmentManager());
vpPager.setAdapter(pagerAdapter);
SmartTabLayout viewPagerTab = (SmartTabLayout) findViewById(R.id.viewpager_tab);
viewPagerTab.setViewPager(vpPager);
}
}
Switch to a FragmentStatePagerAdapter rather than using FragmentPagerAdapter. Also use getChildFragmentManager() instead of getSupportFragmentManager()
The solution was as Pedro Varela mentioned in the comments:
"Hope this works. Add setRetainInstance(true); in onCreate of your internal fragments of the view pager "Control whether a fragment instance is retained across Activity re-creation (such as from a configuration change). This can only be used with fragments not in the back stack. If set, the fragment lifecycle will be slightly different when an activity is recreated""
Thanks
I've been trying to implement a recycler view inside a fragment which displays parsed data using the retrofit library. Whenever I run the project the lists don't show and the monitor says "E/RecyclerView: No adapter attached; skipping layout". Here is my code:
MainActivity:
package com.example.ahmed.newsapp
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.design.widget.TabLayout;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private static final int ACTIVITY_NUM = 0;
// TODO - insert your themoviedb.org API KEY here
private final static String API_KEY = "<API KEY CENSORED>";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find the view pager that will allow the user to swipe between fragments
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
// Create an adapter that knows which fragment should be shown
FragmentAdapter adapter = new FragmentAdapter(getSupportFragmentManager
());
// Set the adapter onto the view pager
viewPager.setAdapter(adapter);
TabLayout ob=(TabLayout) findViewById(R.id.sliding_tabs);
ob.setupWithViewPager(viewPager);
}
}
FragmentAdapter:
package com.example.ahmed.newsapp;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
/**
* Created by ahmed on 3/22/2017.
*/
public class FragmentAdapter extends FragmentPagerAdapter {
private String tabs[]=new String[]{"Home","Family Members","Colors"};
public FragmentAdapter(FragmentManager fm){
super(fm);
}
#Override
public Fragment getItem(int position) {
switch(position){
case 0:
return new HomeActivity();
case 1:
return new HomeActivity();
/* case 2:
return new ColorFragment();*/
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
return tabs[position];
}
#Override
public int getCount() {
return 2;
}
}
NewsAdapter:
package com.example.ahmed.newsapp;
/**
* Created by ahmed on 27-08-17.
*/
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.List;
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.NewsViewHolder> {
private List<News> news;
private int rowLayout;
private Context context;
public static class NewsViewHolder extends RecyclerView.ViewHolder {
LinearLayout moviesLayout;
TextView movieTitle;
TextView data;
TextView movieDescription;
TextView rating;
public NewsViewHolder(View v) {
super(v);
moviesLayout = (LinearLayout) v.findViewById(R.id.movies_layout);
movieTitle = (TextView) v.findViewById(R.id.title);
data = (TextView) v.findViewById(R.id.subtitle);
movieDescription = (TextView) v.findViewById(R.id.description);
rating = (TextView) v.findViewById(R.id.rating);
}
}
public NewsAdapter(List<News> news, Context context) {
this.news = news;
// this.rowLayout = rowLayout;
this.context = context;
}
#Override
public NewsViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item_news, parent, false);
return new NewsViewHolder(view);
}
#Override
public void onBindViewHolder(NewsViewHolder holder, final int position) {
holder.movieTitle.setText(news.get(position).getTitle());
holder.data.setText(news.get(position).getReleaseDate());
holder.movieDescription.setText(news.get(position).getOverview());
holder.rating.setText(news.get(position).getVoteAverage().toString());
}
#Override
public int getItemCount() {
return news.size();
}
}
HomeActivity:
package com.example.ahmed.newsapp;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static android.content.ContentValues.TAG;
public class HomeActivity extends Fragment {
RecyclerView recyclerView;
private final static String API_KEY = "<API KEY CENSORED>";
NewsAdapter adapter;
List<News> news,dummy;
View rootview;
public HomeActivity() {
// Required empty public constructor
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.activity_home, container, false);
if (API_KEY.isEmpty()) {
Toast.makeText(getContext(), "Please obtain your API KEY first from themoviedb.org", Toast.LENGTH_LONG).show();
return rootview;
}
ApiInterface apiService =
ApiClient.getClient().create(ApiInterface.class);
recyclerView = (RecyclerView) rootview.findViewById(R.id.home_page_recycler_view);
adapter= new NewsAdapter(dummy,getContext());
Call<NewsResponse> call = apiService.getTopRatedMovies(API_KEY);
call.enqueue(new Callback<NewsResponse>() {
#Override
public void onResponse(Call<NewsResponse> call, Response<NewsResponse> response) {
news = response.body().getResults();
adapter.notifyDataSetChanged();
adapter=new NewsAdapter(news,getContext());
recyclerView.setAdapter(adapter);
// adapter.setData(news);
Log.d(TAG, "Number of movies received: " + news.size());
}
#Override
public void onFailure(Call<NewsResponse> call, Throwable t) {
// Log error here since request failed
Log.e(TAG, t.toString());
}
});
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
return rootview;
}
}
i think the problem is in your FragmentAdapter class
just remove return null; statement from your FragmentAdapter like below code
#Override
public Fragment getItem(int position) {
Fragment fragment=null;
switch(position){
case 0:
fragment= new HomeActivity();
case 1:
fragment= new HomeActivity();
/* case 2:
return new ColorFragment();*/
}
return fragment;
}
change this
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
recyclerView = (RecyclerView) rootview.findViewById(R.id.home_page_recycler_view);
adapter= new NewsAdapter(dummy,getContext());
You don't need to recreate your adapter when you receive response.
It may looks like:
recyclerView = (RecyclerView) rootview.findViewById(R.id.home_page_recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
adapter = new NewsAdapter(null, getActivity());
recyclerView.setAdapter(adapter);
Call<NewsResponse> call = apiService.getTopRatedMovies(API_KEY);
call.enqueue(new Callback<NewsResponse>() {
#Override
public void onResponse(Call<NewsResponse> call, Response<NewsResponse> response) {
news = response.body().getResults();
adapter.setData(news);
Log.d(TAG, "Number of movies received: " + news.size());
}
...
And in NewsAdapter:
...
public void setData(Collection<News> newData) {
news.clear();
news.addAll(newData);
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return news == null ? 0 : news.size();
}
...