I made an ImageAdapter class that contains images and an activity that contains 2 buttons, on click each one opens a new activity with a viewpager. The 2 viewpagers have different images and this is where my inexperience comes in.
I took the easy way and duplicated the ImageAdapter (named it ImageAdapter2) and linked it to the 2nd viewpager. visual representation
It works fine, but what I'm trying to do is clean it up and do it all through 1 adapter and 1 viewpager. I tried to do it through Intent getStringExtra but it didn't recognize Intent method. Here are my classes:
ImageAdapter (ImageAdapter2 is the same, just has different images in sliderImageId):
package hr.cnzd.prepoznajmoenasilje;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
public class ImageAdapter extends PagerAdapter {
Context mContext;
ImageAdapter(Context context){
this.mContext = context;
}
#Override
public boolean isViewFromObject(View view, Object o){
return view == ((ImageView) o);
}
private int[] sliderImageId = new int[]{
R.drawable.djeca01, R.drawable.djeca02, R.drawable.djeca03, R.drawable.djeca04, R.drawable.djeca05, R.drawable.djeca06, R.drawable.djeca07, R.drawable.djeca08
};
#Override
public Object instantiateItem(ViewGroup viewGroup, int position){
ImageView imageView = new ImageView(mContext);
imageView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setImageResource(sliderImageId[position]);
((ViewPager) viewGroup).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup viewGroup, int position, Object o){
((ViewPager) viewGroup).removeView((ImageView) o);
}
#Override
public int getCount(){
return sliderImageId.length;
}
}
Activity with buttons:
package hr.cnzd.prepoznajmoenasilje;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import androidx.appcompat.app.AppCompatActivity;
public class MA_Savjeti extends AppCompatActivity {
private ImageButton imageButtonDjeca;
private ImageButton imageButtonOdrasli;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ma__savjeti);
imageButtonDjeca = findViewById(R.id.imgBtnDjeca);
imageButtonDjeca.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openActivitySavjetiDjeca();
}
});
imageButtonOdrasli = findViewById(R.id.imgBtnOdrasli);
imageButtonOdrasli.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openActivitySavjetiOdrasli();
}
});
}
public void openActivitySavjetiDjeca() {
Intent intent = new Intent(this, Savjeti_Djeca.class);
intent.putExtra("savjeti", "djeca");
startActivity(intent);
}
public void openActivitySavjetiOdrasli() {
Intent intent = new Intent(this, Savjeti_Odrasli.class);
intent.putExtra("savjeti", "odrasli");
startActivity(intent);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
}
Activity with viewpager (other activity with viewpager has the same code, just calls ImageAdapter2)
package hr.cnzd.prepoznajmoenasilje;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
public class Savjeti_Djeca extends AppCompatActivity {
ViewPager viewPager;
ImageAdapter imageAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.savjeti_djeca);
viewPager = findViewById(R.id.viewpager);
imageAdapter = new ImageAdapter(this);
viewPager.setAdapter(imageAdapter);
}
}
TLDR: I have 2 ImageAdapters and 2 Viewpagers, but I wanna do it through 1 ImageAdapter and 1 Viewpager (2 buttons on a previous activity decide which set of images is shown on the viewpager)
Solved it using ViewPager2 instead of this way.
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;
}
I have a main activity extending ActionBarActivity. In my activity i create a fragment which isn't showing up. I modified the main activity to extend FragmentActivity and in this case the fragment is showing up. Why isn't the fragment showing up when my activity extends ActionBarActivity? I know that ActionBarActivity extends FragmentActivity so in theory ActionBarActivity should support fragments.
Edit: I resolved it. I wouldn't set any content view on my activity. Now that i set it it works when i extend ActionBarActivity. Still is weird that even if i don't set it, when i extend FragmentActivity it works.
This is my main activity code:
package com.example.yamba;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
//import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
public class StatusActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState == null)
{
StatusFragment fragment = new StatusFragment();
FragmentTransaction fr = getSupportFragmentManager().beginTransaction();
fr.add(android.R.id.content, fragment);
fr.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.status, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is my fragment code:
package com.example.yamba;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Toast;
import android.os.AsyncTask;
import android.text.TextWatcher;
import android.text.Editable;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.support.v4.app.Fragment;
import com.marakana.android.yamba.clientlib.YambaClient;
import com.marakana.android.yamba.clientlib.YambaClientException;
public class StatusFragment extends Fragment implements OnClickListener
{
private static final String TAG = "StatusFragment";
private EditText editStatus;
private Button buttonTweet;
private TextView textCount;
private int defaultColor;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
View view = inflater.inflate(R.layout.activity_fragment, container, false);
editStatus = (EditText) view.findViewById (R.id.editStatus);
buttonTweet = (Button) view.findViewById (R.id.buttonTweet);
textCount = (TextView) view.findViewById (R.id.textCount);
buttonTweet.setOnClickListener(this);
defaultColor = textCount.getTextColors().getDefaultColor();
editStatus.addTextChangedListener(new TextWatcher()
{
public void afterTextChanged (Editable s)
{
int count = 140 - editStatus.length();
textCount.setText(Integer.toString(count));
textCount.setTextColor(Color.GREEN);
if(count<20 && count >= 10)
textCount.setTextColor(Color.YELLOW);
else if (count<10)
textCount.setTextColor(Color.RED);
else
textCount.setTextColor(defaultColor);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void onTextChanged (CharSequence s, int start, int b, int c){}
});
return view;
}
public void onClick(View view)
{
String status = editStatus.getText().toString();
Log.d(TAG, "onClicked with status: " + status);
new PostTask().execute(status);
editStatus.getText().clear();
}
private final class PostTask extends AsyncTask<String, Void, String>
{
protected String doInBackground(String... params)
{
YambaClient yambaCloud = new YambaClient("student", "password");
try
{
yambaCloud.postStatus(params[0]);
return "Succesfuly posted!";
}
catch (YambaClientException e)
{
e.printStackTrace();
return "Failed to post to yamba sevice!";
}
}
#Override
protected void onPostExecute (String result)
{
super.onPostExecute(result);
Toast.makeText(StatusFragment.this.getActivity(), result, Toast.LENGTH_LONG).show();
}
}
}
You are calling the FragmentManager method add into the wrong container. The id you provide must reference to a View (usually a layout) that is part of your activity's layout. So android.R.id.content is surely wrong, look into your activity xml layout and find the correct id (maybe is R.id.content (without android) ? )
It appears to be a bug. As a workaround you could try to add fragment inside a post command. It did the trick for me.
new Handler().post(new Runnable() {
#Override
public void run() {
StatusFragment fragment = new StatusFragment();
FragmentTransaction fr = getSupportFragmentManager().beginTransaction();
fr.add(android.R.id.content, fragment);
fr.commit();
}
});
I have a PagerAdapter with two views. Right now I am calling populateList() from the xml by attaching a android:onClick="populateList()" to a button. If I try to call the populateList() from within the Main activity it creates a NullPointerException on my ListView. How do I inflate my view/ListView so that I can use it within the Main activity?
package com.itoxygen.publicsafety;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
public class Main extends Activity {
/** Called when the activity is first created. */
EditText alarmLabel;
ArrayList<String> item = new ArrayList<String>();
Dialog alarmDialog;
ArrayAdapter<String> listAdapter;
ListView list;
private List<String> path = null;
private String root;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
root = Environment.getExternalStorageDirectory().getPath(); //gets the root path of SD card
MyPagerAdapter adapter = new MyPagerAdapter();
ViewPager myPager = (ViewPager) findViewById(R.id.threepageviewer);
myPager.setAdapter(adapter);
myPager.setCurrentItem(0);
}
}
public void populateList(View v) {
list.setAdapter(listAdapter);
}
////////////////////////////////////////SWIPE NAVIGATION STUFF///////////////////////////////////////////////////////////////
/**
*
*/
private class MyPagerAdapter extends PagerAdapter {
/**
* Returns how many pages on the main Activity
*/
public int getCount() {
return 2; //increment this if adding pages
}
public Object instantiateItem(View collection, int position) {
LayoutInflater inflater = (LayoutInflater) collection.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
/*
* Add your layouts here
*/
int resId = 0;
switch (position) {
case 0:
resId = R.layout.activity_main_list;
break;
case 1:
resId = R.layout.activity_main_tile;
break;
}
View view = inflater.inflate(resId, null);
((ViewPager) collection).addView(view, 0);
list = (ListView)findViewById(R.id.list);
listAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, item);
return view;
}
public void destroyItem(View arg0, int arg1, Object arg2) { ((ViewPager) arg0).removeView((View) arg2); }
public void finishUpdate(View arg0) { }
public boolean isViewFromObject(View arg0, Object arg1) { return arg0 == ((View) arg1); }
public void restoreState(Parcelable arg0, ClassLoader arg1) { }
public Parcelable saveState() { return null; }
public void startUpdate(View arg0) { }
}
}
In list.setAdapter(listAdapter); list will be null unless instantiateItem is called first. Move your assignment of list into onCreate()