I have an simple app that displays texts in a RecyclerView. The fab adds new words to the recyclerview list each time it'os clicked.
My problem now is resetting the RecyclerView to its original state (when activity was first created) when I click on Reset in the options menu. I have tried different ways like mRecyclerView.invalidate(); then calling notifydataSetChanged(); on the mAdapter. Also using getRecycledViewPool().clear();. All to no avail.
Here's my MainActivity Code:
package com.example.recyclerview;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.recyclerview.adapters.WordListAdapter;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.LinkedList;
public class MainActivity extends AppCompatActivity {
private final LinkedList<String> mWordList = new LinkedList<>();
private RecyclerView mRecyclerView;
private WordListAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mRecyclerView = findViewById(R.id.recyclerView);
mAdapter = new WordListAdapter(this, mWordList);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
for (int i = 0; i < 20; i++) {
mWordList.addLast("Word " + i);
}
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int mWordListSize = mWordList.size();
mWordList.addLast("Word " + mWordListSize);
mRecyclerView.getAdapter().notifyItemInserted(mWordListSize);
mRecyclerView.smoothScrollToPosition(mWordListSize);
}
});
}
#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);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.reset) {
// Resetting the RecyclerView
mAdapter = new WordListAdapter(this, mWordList);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
return true;
}
return super.onOptionsItemSelected(item);
}
}
and here'os my Adapter Code:
package com.example.recyclerview.adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.recyclerview.R;
import java.util.LinkedList;
public class WordListAdapter extends RecyclerView.Adapter<WordListAdapter.WordViewHolder> {
private final LinkedList<String> mWordList;
private LayoutInflater mInflater;
public WordListAdapter(Context context, LinkedList<String> wordList) {
mInflater = LayoutInflater.from(context);
this.mWordList = wordList;
}
#NonNull
#Override
public WordListAdapter.WordViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = mInflater.inflate(R.layout.wordlist_item, parent, false);
return new WordViewHolder(itemView, this);
}
#Override
public void onBindViewHolder(#NonNull WordListAdapter.WordViewHolder holder, int position) {
String mCurrent = mWordList.get(position);
holder.wordItemView.setText(mCurrent);
}
#Override
public int getItemCount() {
return mWordList.size();
}
class WordViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public final TextView wordItemView;
final WordListAdapter mAdapter;
public WordViewHolder(#NonNull View itemView, WordListAdapter adapter) {
super(itemView);
wordItemView = itemView.findViewById(R.id.word);
this.mAdapter = adapter;
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int mPosition = getLayoutPosition();
String element = mWordList.get(mPosition);
mWordList.set(mPosition, "Clicked" + element);
mAdapter.notifyDataSetChanged();
}
}
}
Extra:
Any help as to how i can manage click efficiently (without having to handle each item click in the adapter??
Thanks
Recycler is displaying views depending on your WordList.
So to reset, clear the data in your LinkedList by mWordList.clear(); and notify the adapter that data has changed by calling mAdapter.notifyDataSetChanged();
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.reset) {
// Resetting the RecyclerView
// to remove all items
mWordList.clear();
// add default items again
for (int i = 0; i < 20; i++) {
mWordList.addLast("Word " + I);
}
mAdapter.notifyDataSetChanged();
return true;
}
return super.onOptionsItemSelected(item);
}
Extra
Don't use LinkedList for storing data. Instead, you can use an ArrayList which is suitable for most of the use cases.
Related
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.
I am trying to make an activity which has a fragment inside with a recyclerView and cards on it. Right now, it only shows the activity, the fragment is empty, and I don't know what is going on here.
This is the code of the activity, the fragment, and the adapter
Activity:
package com.laorden.goodreasons.habits;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.VisibleForTesting;
import android.support.design.widget.NavigationView;
import android.support.test.espresso.IdlingResource;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.Window;
import android.view.WindowManager;
import com.laorden.goodreasons.Injection;
import com.laorden.goodreasons.R;
import com.laorden.goodreasons.statistics.StatisticsActivity;
import com.laorden.goodreasons.util.ActivityUtils;
import com.laorden.goodreasons.util.EspressoIdlingResource;
public class HabitsActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private HabitsPresenter mHabitsPresenter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.habits_act);
Window w = getWindow();
w.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
// Set up the toolbar.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar ab = getSupportActionBar();
ab.setHomeAsUpIndicator(R.drawable.ic_menu);
ab.setDisplayHomeAsUpEnabled(true);
// Set up the navigation drawer.
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerLayout.setStatusBarBackground(R.color.colorPrimaryDark);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
if (navigationView != null) {
setupDrawerContent(navigationView);
}
HabitsFragment habitsFragment =
(HabitsFragment) getSupportFragmentManager().findFragmentById(R.id.contentFrame);
if (habitsFragment == null) {
// Create the fragment
habitsFragment = HabitsFragment.newInstance();
ActivityUtils.addFragmentToActivity(
getSupportFragmentManager(), habitsFragment, R.id.contentFrame);
}
// Create the presenter
mHabitsPresenter = new HabitsPresenter(habitsFragment,
Injection.provideUseCaseHandler());
}
/* // Load previously saved state, if available.
if (savedInstanceState != null) {
TasksFilterType currentFiltering =
(TasksFilterType) savedInstanceState.getSerializable(CURRENT_FILTERING_KEY);
mTasksPresenter.setFiltering(currentFiltering);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putSerializable(CURRENT_FILTERING_KEY, mTasksPresenter.getFiltering());
super.onSaveInstanceState(outState);
}*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// Open the navigation drawer when the home icon is selected from the toolbar.
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.list_navigation_menu_item:
// Do nothing, we're already on that screen
break;
case R.id.statistics_navigation_menu_item:
Intent intent =
new Intent(HabitsActivity.this, StatisticsActivity.class);
startActivity(intent);
break;
default:
break;
}
// Close the navigation drawer when an item is selected.
menuItem.setChecked(true);
mDrawerLayout.closeDrawers();
return true;
}
});
}
#VisibleForTesting
public IdlingResource getCountingIdlingResource() {
return EspressoIdlingResource.getIdlingResource();
}
}
Fragment:
package com.laorden.goodreasons.habits;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import com.laorden.goodreasons.R;
import com.laorden.goodreasons.habits.domain.model.Habit;
import java.util.ArrayList;
import java.util.List;
public class HabitsFragment extends android.support.v4.app.Fragment implements HabitsContract.View {
private HabitsContract.Presenter mPresenter;
private HabitsAdapter mListAdapter;
private RecyclerView recyclerView;
public HabitsFragment() {
// Requires empty public constructor
}
public static HabitsFragment newInstance() {
return new HabitsFragment();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
List<Habit> habitsList = new ArrayList<>();
habitsList.add(new Habit(R.drawable.smoke,"Quit smoking",300));
habitsList.add(new Habit(R.drawable.books,"Read more",600));
habitsList.add(new Habit(R.drawable.sleep,"Get more sleep",600));
mListAdapter = new HabitsAdapter(getContext(),habitsList);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.habits_frag, container, false);
recyclerView = root.findViewById(R.id.rv_list);
recyclerView.setAdapter(mListAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
return root;
}
#Override
public void onResume() {
super.onResume();
mPresenter.start();
}
#Override
public void setLoadingIndicator(boolean active) {
}
#Override
public void showHabits(List<Habit> habits) {
}
#Override
public void showHabitDetailsUi(String habitId) {
}
#Override
public boolean isActive() {
return false;
}
#Override
public void setPresenter(HabitsContract.Presenter presenter) {
mPresenter = presenter;
}
}
Adapter:
package com.laorden.goodreasons.habits;
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.ImageView;
import android.widget.TextView;
import com.laorden.goodreasons.R;
import com.laorden.goodreasons.habits.domain.model.Habit;
import java.util.List;
public class HabitsAdapter extends RecyclerView.Adapter<HabitsAdapter.myViewHolder> {
Context mContext;
List<Habit> mData;
public HabitsAdapter(Context mContext, List<Habit> mData) {
this.mContext = mContext;
this.mData = mData;
}
#Override
public myViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View v = inflater.inflate(R.layout.card_item,parent,false);
return new myViewHolder(v);
}
#Override
public void onBindViewHolder(myViewHolder holder, int position) {
holder.background_image.setImageResource(mData.get(position).getBackground());
holder.tv_title.setText(mData.get(position).getHabitName());
holder.tv_nbSubscribers.setText(mData.get(position).getNumSubscribers() + " Joined");
}
#Override
public int getItemCount() {
return 0;
}
public class myViewHolder extends RecyclerView.ViewHolder {
ImageView background_image;
TextView tv_title,tv_nbSubscribers;
public myViewHolder(View itemView) {
super(itemView);
background_image = itemView.findViewById(R.id.card_background);
tv_title = itemView.findViewById(R.id.card_title);
tv_nbSubscribers = itemView.findViewById(R.id.card_numberUsers);
}
}
}
If you need any other code snippets, please tell me (maybe the xml
layouts)
Thanks
That is because you are returning 0 in the getItemCount method
Change this :
#Override
public int getItemCount() {
return 0;
}
To this:
#Override
public int getItemCount() {
return (mData != null ? mData.size():0);
}
you should set layout manager first
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.habits_frag, container, false);
recyclerView = root.findViewById(R.id.rv_list);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(mListAdapter);
return root;
}
also you need to change the getItemCount into
#Override
public int getItemCount() {
if(mData!=null){return mData.size();}else return 0;
}
The reason you are getting empty list because your method getItemCount returns 0.
Here is the modified method.
#Override
public int getItemCount() {
return mData!=null ? mData.size():0;
}
#beginner ...i created the cards list here is the image using list view
i want to get to the new screen frm the click on the card made in list view...please help me to solve this problem .... please give me the full details of the ways by which i can do the task to solve my problems....
.... here is what i coded::::
Main_Activity.java
package com.android.mezohn.nepstudy.app;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.android.mezohn.nepstudy.Adapter.subjectAdapter;
import com.android.mezohn.nepstudy.R;
import com.android.mezohn.nepstudy.model.ListDetails;
import com.android.mezohn.nepstudy.model.model;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private ListView listView;
private ArrayList<model>models;
private subjectAdapter subjectAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
listView = (ListView)findViewById(R.id.list_view);
models = ListDetails.getList();
subjectAdapter = new subjectAdapter(MainActivity.this,models);
listView.setAdapter(subjectAdapter);
FloatingActionButton fab = (FloatingActionButton) 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();
}
});
}
#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);
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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
model.java
package com.android.mezohn.nepstudy.model;
/**
* Created by ecspc on 25/10/2017.
*/
public class model {
private int subjectImage;
private String subjectTitle;
private String count;
public model(int subjectImage, String subjectTitle, String count) {
this.subjectImage = subjectImage;
this.subjectTitle = subjectTitle;
this.count = count;
}
public int getSubjectImage() {
return subjectImage;
}
public void setSubjectImage(int subjectImage) {
this.subjectImage = subjectImage;
}
public String getCount() {
return count;
}
public void setCount(String count) {
this.count = count;
}
public String getSubjectTitle() {
return subjectTitle;
}
public void setSubjectTitle(String subjectTitle) {
this.subjectTitle = subjectTitle;
}
}
subjectAdapter.java
package com.android.mezohn.nepstudy.Adapter;
import android.content.Context;
import android.graphics.ColorSpace;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.mezohn.nepstudy.R;
import com.android.mezohn.nepstudy.model.model;
import java.util.ArrayList;
/**
* Created by ecspc on 25/10/2017.
*/
public class subjectAdapter extends BaseAdapter {
private Context context;
private ArrayList<model> models;
public subjectAdapter(Context context, ArrayList<model> models) {
this.context = context;
this.models = models;
}
#Override
public int getCount() {
return models.size();
}
#Override
public Object getItem(int position) {
return models.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView ==null){
convertView = View.inflate(context, R.layout.list_view,null);
ImageView images = convertView.findViewById(R.id.cardImage);
TextView title = convertView.findViewById(R.id.cardTitle);
TextView count = convertView.findViewById(R.id.count);
model model = models.get(position);
images.setImageResource(model.getSubjectImage());
title.setText(model.getSubjectTitle());
count.setText(model.getCount());
}
return convertView;
}
}
ListDetails.java
package com.android.mezohn.nepstudy.model;
import com.android.mezohn.nepstudy.R;
import java.util.ArrayList;
/**
* Created by ecspc on 25/10/2017.
*/
public class ListDetails {
public static ArrayList<model> getList(){
ArrayList<model> subjectList = new ArrayList<>();
subjectList.add(new model(R.drawable.phy,"Physics","4 chapters available"));
subjectList.add(new model(R.drawable.che,"Chemistry","5 chapters available "));
subjectList.add(new model(R.drawable.que,"Model Questions","10 model Questions available"));
return subjectList;
}
}
i am a beginner so i hope i would get sufficient help from it.
So it appears you have not attempted to add a listener to your ListView. You can do this via AdapterView.OnItemClickListener
listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
//.. launch your new activity here using Intent
Intent intent = new Intent(MainActivity.this, NewActivity.class);
startActivity(intent);
}
});
Another note, you should really get better at naming your classes. Recommended reading: Effective Java
You should also read: Making a listview scroll smooth which talks about the ViewHolder pattern, or simply move to a RecyclerView once you know a bit more android.
I am trying to write different functionalities for my FloatingActionButton depending on the fragment that the mainActivity is currently hosting. Yet for for reason in my onClick() method, getSupportFragmentManager().findFragmentById() returns null.
I haven't seen any examples of this question implemented with a viewpager and I am curious if there is a different approach I have to take.
MainActivity
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
public class MainActivity extends FragmentActivity {
private Adapter mAdapter;
private ViewPager mViewPager;
private static FloatingActionButton bButton;
private static String UID;
private Intent intent;
public static String getUID(){
return UID;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdapter = new Adapter(getSupportFragmentManager());
mViewPager = (ViewPager)findViewById(R.id.vPager);
mViewPager.setAdapter(mAdapter);
intent = getIntent();
UID = intent.getStringExtra("uid");
bButton = (FloatingActionButton)findViewById(R.id.bButton);
bButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragContainer);
if(fragment == null){
Log.e("TAG","FRAGMENT IS NULL!!");
}
else{
Log.e("TAG","FRAGMENT IS NOT NULL!!");
}
}
});
}
}
NewsFeedFragment
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.mycompany.neighbors.R;
import com.mycompany.neighbors.SinglePost;
import java.util.ArrayList;
/**
* Created by joshua on 5/25/2016.
*/
public class NewsFeedFragment extends ListFragment implements AdapterView.OnItemClickListener{
private ListView lv;
private TextView tvUserName;
private TextView tvStatus;
private ArrayList<SinglePost> posts = new ArrayList<>();
private static final String POSTS_PATH = "MY_PATH";
private Firebase postsRef;
// private static final String FRAGMENT_POST = "post";
public void postFragment(){
Log.d("TAG", "Doing something else");
PostFragment postFragment = new PostFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.fragContainer,postFragment)
.addToBackStack(null)
.commit();
}
#Override
public void onViewCreated(View v, Bundle s){
lv = getListView();
lv.setOnItemClickListener(this);
}
#Override
public void onCreate(Bundle savedInstance){
super.onCreate(savedInstance);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.fragment_post_feed_item,parent,false);//changed
tvUserName = (TextView)v.findViewById(R.id.tvUN);
tvStatus = (TextView)v.findViewById(R.id.tvStatus);
postsRef = new Firebase(POSTS_PATH);
postsRef.addChildEventListener(new com.firebase.client.ChildEventListener() {
#Override
public void onChildAdded(com.firebase.client.DataSnapshot dataSnapshot, String s) {
SinglePost post = dataSnapshot.getValue(SinglePost.class);
post.setKey(dataSnapshot.getKey());
posts.add(0, post);
if(posts.size() > 0) {
PostAdapter adapter = new PostAdapter(posts);
setListAdapter(adapter);
}else{
Toast toast = Toast.makeText(getActivity(),"No data", Toast.LENGTH_SHORT);
toast.show();
}
}
#Override
public void onChildChanged(com.firebase.client.DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(com.firebase.client.DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(com.firebase.client.DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
return v;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id){
SinglePost p = ((PostAdapter) getListAdapter()).getItem(position);
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
}
private class PostAdapter extends ArrayAdapter<SinglePost>{
public PostAdapter(ArrayList<SinglePost> singlePost){
super(getActivity(),android.R.layout.simple_list_item_1,singlePost);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
if(convertView == null){
convertView = getActivity().getLayoutInflater().inflate(R.layout.fragment_post_feed_item,null);
}
SinglePost p = getItem(position);
TextView tvUserName = (TextView)convertView.findViewById(R.id.tvUN);
tvUserName.setText(p.getUserName());
TextView tvStatus = (TextView)convertView.findViewById(R.id.tvStatus);
tvStatus.setText(p.getStatus());
return convertView;
}
}
}
I have 2 other fragments but i'll post one as an example. Here is my adapter for the viewpager.
Adapter
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.mycompany.neighbors.Fragments.MapFragment;
import com.mycompany.neighbors.Fragments.NewsFeedFragment;
import com.mycompany.neighbors.Fragments.ProfileFragment;
/**
* Created by joshua on 5/25/2016.
*/
public class Adapter extends FragmentPagerAdapter {
private String Fragment[] = {"Posts" , "Map" , "Profile"};
public Adapter(FragmentManager fm){
super (fm);
}
#Override
public Fragment getItem(int position) {
switch(position){
case 0:
return new NewsFeedFragment();
case 1:
return new MapFragment();
case 2:
return new ProfileFragment();
default:
return null;
}
}
#Override
public int getCount(){return Fragment.length;}
#Override
public CharSequence getPageTitle(int position) {
return Fragment[position];
}
}
Please check below link, It has very good explanation for your problem:
http://tamsler.blogspot.in/2011/11/android-viewpager-and-fragments-part-ii.html
Or you can try below code snippet:
1.Where you add fragment in view pager or view pager adapter:
MyFragment myFragment = MyFragment.newInstance();
mPageReferenceMap.put(index, "Some Tag");
getSupportFragmentManager().beginTransaction().add(myFragment,"Some Tag").commit();
2.To get the tag for the currently visible page, you then call:
int index = mViewPager.getCurrentItem();
String tag = mPageReferenceMap.get(index);
3.and then get the fragment page:
Fragment myFragment = getSupportFragmentManager().findFragmentByTag(tag);
I have a listview that uses a custom arrayadapter that loads a layout with text + a radiobutton. The user should only be able to select a single item in the list at a time - so basically only one radio button should be 'checked' at any time. This works perfectly except when the activity is recreated, like when the screen is rotated. I can't figure out why it's doing this, so maybe you all can think of something?
Here's the code for the activity that has the listview:
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.support.v4.app.NavUtils;
import android.widget.AdapterView;
public class TimeForm extends Activity implements AdapterView.OnItemClickListener {
private MyArrayAdapter maa;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_time_form);
// Show the Up button in the action bar.
getActionBar().setDisplayHomeAsUpEnabled(true);
ListView lv = (ListView) findViewById(R.id.listView1);
lv.setItemsCanFocus(false);
String listitems[] = new String[16];
listitems[0] = "Other";
for(int i = 1; i < 16; i++)
{
listitems[i] = "Job " + i;
}
maa = new MyArrayAdapter(this, R.layout.layout_list, listitems);
if(savedInstanceState != null)
maa.selIndex = savedInstanceState.getInt("selIndex");
lv.setAdapter(maa);
lv.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
EditText et = (EditText) this.findViewById(R.id.editText1);
if(position == 0)
{
et.setVisibility(View.VISIBLE);
} else {
et.setVisibility(View.GONE);
}
if(maa.selItem != null)
{
RadioButton rOld = (RadioButton) maa.selItem.findViewById(R.id.radioButton1);
rOld.setChecked(false);
}
RadioButton r = (RadioButton) view.findViewById(R.id.radioButton1);
r.setChecked(true);
maa.selIndex = position;
maa.selItem = view;
}
public void onSaveInstanceState(Bundle b)
{
b.putInt("selIndex", maa.selIndex);
super.onSaveInstanceState(b);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_time_form, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
Code for MyArrayAdapter class:
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.RadioButton;
import android.widget.TextView;
public class MyArrayAdapter extends ArrayAdapter<String> {
private Context context;
private String[] strings;
private int layoutID;
public int selIndex;
public View selItem;
public MyArrayAdapter(Context c, int id, String[] values)
{
super(c, id, values);
selIndex = -1;
selItem = null;
this.strings = values;
this.context = c;
layoutID = id;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rView = inflater.inflate(layoutID, parent, false);
TextView tv = (TextView) rView.findViewById(R.id.textView1);
tv.setText(strings[position]);
if(position == selIndex)
{
RadioButton r = (RadioButton) rView.findViewById(R.id.radioButton1);
r.setChecked(true);
selItem = rView;
}
return rView;
}
}
Well, first thing's first, with regards to 're-creating' the view.. check out http://developer.android.com/guide/topics/resources/runtime-changes.html.
You can define public void onConfigurationChanged(Configuration newConfig) to ensure that your activity isn't recreated on rotation, for example.
That said, if you want to persist the values, you'll have to actually do that, and then apply any selections to your collection passed into your ArrayAdapter.
I figured it out. I'm not sure it's the best possible solution, but it works and doesn't cause any noticeable performance loss. ^_^
In the TimeForm activity's onItemClick() method, i added this at the bottom:
ListView lv = (ListView) findViewById(R.id.listView1);
lv.invalidateViews();
This forces the listview to redraw all the child views. Thanks to everyone who took the time to help me figure this out.