a problem in my code arose after fixing some other bugs. My activity which "should" show detailed information of movies doesn't get displayed properly instead, just a blank activity opens.
my detail activity:
public class detailsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
Intent intent = getIntent();
String fragment = intent.getExtras().getString("FRAGMENT");
if(fragment.equals("MOVIE")) {
MovieGridFragment frag = new MovieGridFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fl_detail_fragment,frag).commit();
} else {
getFragmentManager().beginTransaction().replace(R.id.fl_detail_fragment, new displayMovieDetails()).commit();
}
}}
the mainActivity :
public class MainActivity extends AppCompatActivity implements clickInterfaceHelper {
public static String sorterString = null;
public static String urlBase = "https://api.themoviedb.org/3/movie/";
public static String urlFinal = null;
RequestQueue requestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState == null) {
MovieGridFragment fragment = new MovieGridFragment();
fragment.setClickListener(this);
getSupportFragmentManager().beginTransaction()
.add(R.id.activity_container, fragment)
.commit();
movieData.movieDataPosition = 0;
}
if(savedInstanceState != null) {
sorterString = savedInstanceState.getString("SORTER");
}
if(savedInstanceState == null)
movieData.movieDataPosition = 0;
if(sorterString==null)
sorterString="popular?";
if(sorterString!="favorite" && sorterString!=null) {
if(networkChecker.isNetworkAvailableChecker(this)) {
movieRequest();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu_act, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == R.id.m_popularity_action) {
if(sorterString != "popular?") {
sorterString = "popular?";
if(networkChecker.isNetworkAvailableChecker(this))
movieRequest();
}
return true;
}
if(id == R.id.m_action_voter) {
if(sorterString != "top_rated?") {
sorterString = "top_rated?";
if(networkChecker.isNetworkAvailableChecker(this))
movieRequest();
}
return true;
}
if(id == R.id.m_favorite_btn) {
if(sorterString != "favorite") {
SQLiteOpenHelper helper = new movieDataDbHelper(this);
SQLiteDatabase database = helper.getReadableDatabase();
Cursor cursor= database.query(movieDataContract.contractEntry.TABLE_NAME,
new String[] {
movieDataContract.contractEntry.ID,
movieDataContract.contractEntry.IMG_PATH},null,null,null,null,null);
if(cursor.getCount() == 0) {
Toast.makeText(this, "there are no favorite movies yet!",Toast.LENGTH_SHORT).show();
} else {
sorterString = "favorite";
showFavoriteFragment();
}
database.close();
helper.close();
cursor.close();
}
return true;
}
return super.onOptionsItemSelected(item);
}
public void showFavoriteFragment() {
favoriteMoviesDetailsFragment fragment = new favoriteMoviesDetailsFragment();
try {
getFragmentManager().beginTransaction().replace(R.id.activity_container,fragment).commit();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
outState.putString("SORTER", sorterString);
outState.putInt("POSITION",movieData.movieDataPosition);
super.onSaveInstanceState(outState, outPersistentState);
}
public void movieRequest() {
final MovieGridFragment gridFragment = new MovieGridFragment();
gridFragment.setClickListener(this);
urlFinal = urlBase + sorterString + movieData.apiKey;
urlFinal.trim();
requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, urlFinal, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray array = response.getJSONArray("results");
movieData.movieDataArray = new movieData[array.length()];
for (int i = 0; i < array.length(); i++) {
movieData movie = new movieData();
JSONObject jsonObject = array.getJSONObject(i);
movie.setMovieId(jsonObject.getString("id"));
movie.setMovieImagePath(jsonObject.getString("poster_path"));
movie.setMovieTitle(jsonObject.getString("original_title"));
movie.setMoviePlot(jsonObject.getString("overview"));
movie.setMovieVoting(jsonObject.getString("vote_average"));
movie.setMovieReleaseDate(jsonObject.getString("release_date"));
movieData.movieDataArray[i] = movie;
}
gridFragment.movieDataList = Arrays.asList(movieData.movieDataArray);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.activity_container, gridFragment);
try {
transaction.commitAllowingStateLoss();
} catch (Exception e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("volley", String.valueOf(error));
}
}
);
requestQueue.add(jsonObjectRequest);
}
#Override
public void clickOnItem(int id) {
movieData.movieDataPosition = id;
if(movieData.movieDataArray == null) {
movieRequest();
} else {
Intent intent = new Intent(this, detailsActivity.class);
intent.putExtra("FRAGMENT","MOVIE");
startActivity(intent);
}
}
#Override
public void favoriteMovieItem(int movieId) {
movieData.dbPosition = movieId;
Intent intent = new Intent(this,detailsActivity.class);
intent.putExtra("FRAGMENT","favorite");
startActivity(intent);
}
}
and the movieFragment which should display the data:
public class MovieGridFragment extends Fragment {
public clickInterfaceHelper clickListener;
private GridView movieGridView;
private int index;
public List<movieData> movieDataList = new ArrayList<>();
public MovieGridFragment() {} //empty constructor
#Override
public void onAttach(Context context) {
//this.clickListener = (clickInterfaceHelper) context;
super.onAttach(context);
}
public void setClickListener(clickInterfaceHelper listener) {
this.clickListener = listener;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
setHasOptionsMenu(true);
if(movieDataList.isEmpty() && networkChecker.isNetworkAvailableChecker(getContext())) {
movieDataList = new ArrayList<movieData>();
}
if(!movieDataList.isEmpty() && !networkChecker.isNetworkAvailableChecker(getContext())) {
movieDataList = new ArrayList<movieData>();
}
if(savedInstanceState != null) {
index = savedInstanceState.getInt("INDEX");
if(movieDataList.isEmpty()) {
movieDataList.addAll(Arrays.asList((movieData[]) savedInstanceState.getSerializable("OLDMOVIEDATA")));
}
}
View rootView = inflater.inflate(R.layout.movie_display_fragment, container, false);
movieGridView = (GridView) rootView.findViewById(R.id.gv_movie_display);
movieAdapter adapter = new movieAdapter(getActivity(),movieDataList);
adapter.notifyDataSetChanged();
movieGridView.setAdapter(adapter);
movieGridView.smoothScrollToPosition(index);
movieGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(clickListener != null)
clickListener.clickOnItem(position);
}
});
return rootView;
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putSerializable("OLDMOVIEDATA",movieData.movieDataArray);
outState.putInt("INDEX",movieGridView.getFirstVisiblePosition());
super.onSaveInstanceState(outState);
}
}
the activity_details layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".detailsActivity">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fl_detail_fragment">
</FrameLayout>
</LinearLayout>
You should use getSupportFragmentManager().beginTransaction().add() for the first time.
Then when you added a fragment before you should use getSupportFragmentManager().beginTransaction().replace()
EDIT
public class MovieGridFragment extends Fragment {
public clickInterfaceHelper clickListener;
private GridView movieGridView;
private int index;
public List<movieData> movieDataList = new ArrayList<>();
public void setMovieDataList(List<movieData> movieDataList) {
this.movieDataList = movieDataList;
}
public void setClickListener(clickInterfaceHelper listener) {
this.clickListener = listener;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
setHasOptionsMenu(true);
View rootView = inflater.inflate(R.layout.movie_display_fragment, container, false);
movieGridView = (GridView) rootView.findViewById(R.id.gv_movie_display);
if (movieDataList != null) {
initMovieGrid();
}
return rootView;
}
private void initMovieGrid() {
movieAdapter adapter = new movieAdapter(getActivity(), movieDataList);
adapter.notifyDataSetChanged();
movieGridView.setAdapter(adapter);
movieGridView.smoothScrollToPosition(index);
movieGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (clickListener != null)
clickListener.clickOnItem(position);
}
});
}
}
To use the fragment:
MovieGridFragment fragment = new MovieGridFragment();
fragment.setClickListener(this);
fragment.setMovieDataList(movieDataList);
getSupportFragmentManager().beginTransaction()
.add(R.id.activity_container, fragment).commit();
If you don't have the the list of movies before you use your fragment, you could use this code for fragment:
public class MovieGridFragment extends Fragment {
public clickInterfaceHelper clickListener;
private GridView movieGridView;
private int index;
public List<movieData> movieDataList = new ArrayList<>();
public void setMovieDataList(List<movieData> movieDataList) {
this.movieDataList = movieDataList;
if (movieDataList != null) {
initMovieGrid();
}
}
public void setClickListener(clickInterfaceHelper listener) {
this.clickListener = listener;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
setHasOptionsMenu(true);
View rootView = inflater.inflate(R.layout.movie_display_fragment, container, false);
movieGridView = (GridView) rootView.findViewById(R.id.gv_movie_display);
return rootView;
}
private void initMovieGrid() {
movieAdapter adapter = new movieAdapter(getActivity(), movieDataList);
adapter.notifyDataSetChanged();
movieGridView.setAdapter(adapter);
movieGridView.smoothScrollToPosition(index);
movieGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (clickListener != null)
clickListener.clickOnItem(position);
}
});
}
}
Then create your fragment without using setMovieDataList() and when you get the movies data, use the method setMovieDataList()
public class MainActivity extends AppCompatActivity implements clickInterfaceHelper {
//...
MovieGridFragment mFragment;
//...
Create:
mFragment = new MovieGridFragment();
fragment.setClickListener(this);
getSupportFragmentManager().beginTransaction()
.add(R.id.activity_container, fragment).commit();
After you get the data:
mFragment.setMovieDataList(movieDataList);
You should prepend Intent extras with an unique identifier, but i'm not sure if this is what's causing the problem.
I'm very sorry for your effort but i'm just plain out stupid...
I opened the wrong Fragment....
Related
I'm getting the object from modelView as you guys see.
Every thing is perfectly working apart from my viewpager fragment when I first come to my pager fragment it shows data when I go through forward and then come backward it disappears my data and my layout structure.
My viewModel have data always have a data but my recyclerview is not showing it.
BrandFragment is a base fragment having viewpager in it.
BrandFragment :
public class BrandFragment extends Fragment {
#BindView(R.id.brandtablayout)
TabLayout brandtablayout;
#BindView(R.id.brandpager)
ViewPager brandpager;
#BindView(R.id.backgroundImage)
ImageView backgroundImage;
#BindView(R.id.brandIcon)
CircleImageView brandIcon;
#BindView(R.id.brandName)
TextView brandName;
#BindView(R.id.brandTagLine)
TextView brandTagLine;
#BindView(R.id.brandRatingBar)
RatingBar brandRatingBar;
#BindView(R.id.noInternet)
ImageView noInternet;
private Brand brand;
int chipId;
private KProgressHUD mProgressBar;
private ShareViewModel shareViewModel;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_brand, container, false);
brandpager = view.findViewById(R.id.brandpager);
brandtablayout = view.findViewById(R.id.brandtablayout);
backgroundImage = view.findViewById(R.id.backgroundImage);
brandIcon = view.findViewById(R.id.brandIcon);
brandName = view.findViewById(R.id.brandName);
brandTagLine= view.findViewById(R.id.brandTagLine);
brandRatingBar = view.findViewById(R.id.brandRatingBar);
noInternet = view.findViewById(R.id.noInternet);
brandtablayout.addTab(brandtablayout.newTab().setText("Product"));
brandtablayout.addTab(brandtablayout.newTab().setText("Profile"));
brandtablayout.setTabGravity(TabLayout.GRAVITY_FILL);
BrandProfileViewPagerAdapter brandProfileAdapter = new BrandProfileViewPagerAdapter(getFragmentManager(), brandtablayout.getTabCount());
brandpager.setAdapter(brandProfileAdapter);
brandtablayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
brandpager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
progressbar("Getting Brand Detail","Please wait...");
return view;
}
private void getBrandDetails() {
WebServiceFactory.getInstance().getBrandDetails(chipId).enqueue(new Callback<Brand>() {
#Override
public void onResponse(Call<Brand> call, Response<Brand> response) {
if (response.body().getFlag() == 1) {
brand = response.body();
shareViewModel.setBrandProductsMutableLiveData(brand.getBrandProducts());
shareViewModel.setBrandSpecificationsMutableLiveData(brand.getBrandSpecifications());
brandProfileDetails();
mProgressBar.dismiss();
}else {
mProgressBar.dismiss();
}
}
#Override
public void onFailure(Call<Brand> call, Throwable t) {
mProgressBar.dismiss();
}
});
}
private void brandProfileDetails(){
if (brand.getBrandSpecifications() != null){
brandRatingBar.setRating(brand.getBrandSpecifications().getBrandRates());
brandName.setText(brand.getBrandSpecifications().getBrandName());
Picasso.get().load(AppConstants.imagePath(brand.getBrandSpecifications().getBrandBg())).into(backgroundImage);
brandTagLine.setText(brand.getBrandSpecifications().getBrandSlogan());
Picasso.get().load(AppConstants.imagePath(brand.getBrandSpecifications().getBrandIcon())).into(brandIcon);
}
mProgressBar.dismiss();
}
#Override
public void onViewCreated (#NonNull View view, #Nullable Bundle savedInstanceState){
super.onViewCreated(view, savedInstanceState);
shareViewModel = ViewModelProviders.of((FragmentActivity) requireActivity()).get(ShareViewModel.class);
shareViewModel.getChipId().observe(getViewLifecycleOwner(), new Observer<Integer>() {
#Override
public void onChanged(Integer id) {
chipId =id;
if (InternetConnection.checkConnection(getContext())) {
// Internet Available...
noInternet.setVisibility(View.GONE);
getBrandDetails();
} else {
noInternet.setVisibility(View.VISIBLE);
mProgressBar.dismiss();
Toast.makeText(getContext(), "Check your internet Connection", Toast.LENGTH_SHORT).show();
// Internet Not Available...
}
}
});
}
private void progressbar(String title, String detail){
mProgressBar = KProgressHUD.create(getContext())
.setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
.setLabel(title)
.setDetailsLabel(detail)
.setCancellable(false)
.setAnimationSpeed(2)
.setDimAmount(0.5f)
.show();
}
}
BrandProductFragment :
public class BrandProductFragment extends Fragment implements RecyclerviewOnClickInterface, CategoryRecyclerviewInterface, ChipsInterface, MyButtonClickListener {
int tabCount;
#BindView(R.id.brandPopularProduct)
TextView brandPopularProduct;
#BindView(R.id.brandNewProduct)
TextView brnadNewProduct;
#BindView(R.id.brandHighestProduct)
TextView brandHighestProduct;
#BindView(R.id.brandLowestProduct)
TextView brandLowestProduct;
#BindView(R.id.brandProductRecyclerview)
RecyclerView brandProductRecyclerview;
BrandProfilePopularAdapter brandProfilePopularAdapter;
BrandNewReleaseAdapter brandNewReleaseAdapter;
BrandProductHighestAdapter brandProductHighestAdapter;
BrandLowestAdapter brandLowestAdapter;
BrandProducts brandProductData;
ShareViewModel shareViewModel;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_brand_product, container, false);
tabCount = 0;
brandPopularProduct = view.findViewById(R.id.brandPopularProduct);
brnadNewProduct = view.findViewById(R.id.brandNewProduct);
brandHighestProduct = view.findViewById(R.id.brandHighestProduct);
brandLowestProduct = view.findViewById(R.id.brandLowestProduct);
brandProductRecyclerview = view.findViewById(R.id.brandProductRecyclerview);
buttonOnClick();
return view;
}
private void buttonOnClick() {
brandPopularProduct.setOnClickListener(v -> {
tabCount = 1;
tabSelector();
if (brandProductData != null) {
getBrandProductPopular(brandProductData);
}
});
brnadNewProduct.setOnClickListener(v -> {
tabCount = 2;
tabSelector();
if (brandProductData != null) {
getBrandProductNewRelease();
}
});
brandHighestProduct.setOnClickListener(v -> {
tabCount = 3;
tabSelector();
if (brandProductData != null) {
getBrandProductHighest();
}
});
brandLowestProduct.setOnClickListener(v -> {
tabCount = 4;
tabSelector();
if (brandProductData != null) {
getBrandProductLowest();
}
});
}
private void tabSelector() {
if (tabCount == 1) {
brandPopularProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor));
brandPopularProduct.setTextSize(20);
brnadNewProduct.setTextSize(18);
brandLowestProduct.setTextSize(18);
brandHighestProduct.setTextSize(18);
brnadNewProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor2));
brandHighestProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor2));
brandLowestProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor2));
} else if (tabCount == 2) {
brnadNewProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor));
brandPopularProduct.setTextSize(18);
brnadNewProduct.setTextSize(20);
brandLowestProduct.setTextSize(18);
brandHighestProduct.setTextSize(18);
brandPopularProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor2));
brandHighestProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor2));
brandLowestProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor2));
} else if (tabCount == 3) {
brandHighestProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor));
brandPopularProduct.setTextSize(18);
brnadNewProduct.setTextSize(18);
brandLowestProduct.setTextSize(18);
brandHighestProduct.setTextSize(20);
brnadNewProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor2));
brandPopularProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor2));
brandLowestProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor2));
} else if (tabCount == 4) {
brandLowestProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor));
brandPopularProduct.setTextSize(18);
brnadNewProduct.setTextSize(18);
brandLowestProduct.setTextSize(20);
brandHighestProduct.setTextSize(18);
brnadNewProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor2));
brandHighestProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor2));
brandPopularProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor2));
}
}
private void getBrandProductPopular(BrandProducts brandProductData) {
if (brandProductData.getPOPULARPRODUCTS() != null){
brandProfilePopularAdapter = new BrandProfilePopularAdapter(getContext(), brandProductData.getPOPULARPRODUCTS(), this);
GridLayoutManager mLayoutManager = new GridLayoutManager(getContext(), 2);
brandProductRecyclerview.setLayoutManager(mLayoutManager);
brandProductRecyclerview.setAdapter(brandProfilePopularAdapter);
recyclerviewAnimation(brandProductRecyclerview);
}
}
private void getBrandProductNewRelease() {
if ( brandProductData.getNEWRELEASEPRODUCTS() != null){
brandNewReleaseAdapter = new BrandNewReleaseAdapter(getContext(), brandProductData.getNEWRELEASEPRODUCTS(), this);
GridLayoutManager mLayoutManager = new GridLayoutManager(getContext(), 2);
brandProductRecyclerview.setLayoutManager(mLayoutManager);
brandProductRecyclerview.setAdapter(brandNewReleaseAdapter);
recyclerviewAnimation(brandProductRecyclerview);
}
}
private void getBrandProductHighest() {
if (brandProductData.getHIGHESTPRODUCTS() != null){
brandProductHighestAdapter = new BrandProductHighestAdapter(getContext(), brandProductData.getHIGHESTPRODUCTS(), this);
GridLayoutManager mLayoutManager = new GridLayoutManager(getContext(), 2);
brandProductRecyclerview.setLayoutManager(mLayoutManager);
brandProductRecyclerview.setAdapter(brandProductHighestAdapter);
recyclerviewAnimation(brandProductRecyclerview);
}
}
private void getBrandProductLowest() {
if ( brandProductData.getLOWESTPRODUCTS() != null){
brandLowestAdapter = new BrandLowestAdapter(getContext(), brandProductData.getLOWESTPRODUCTS(), this);
GridLayoutManager mLayoutManager = new GridLayoutManager(getContext(), 2);
brandProductRecyclerview.setLayoutManager(mLayoutManager);
brandProductRecyclerview.setAdapter(brandLowestAdapter);
recyclerviewAnimation(brandProductRecyclerview);
}
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
shareViewModel = ViewModelProviders.of((FragmentActivity) getContext()).get(ShareViewModel.class);
shareViewModel.getBrandProduct().observe(getViewLifecycleOwner(), new Observer<BrandProducts>() {
#Override
public void onChanged(BrandProducts brandProducts) {
Log.e("getBrands", brandProducts.toString());
brandProductData = brandProducts;
getBrandProductPopular(brandProductData);
}
});
}
private void recyclerviewAnimation(RecyclerView recyclerView) {
Context context = recyclerView.getContext();
LayoutAnimationController layoutAnimationController = AnimationUtils.loadLayoutAnimation(context, R.anim.layout_animation_fall_down);
recyclerView.setLayoutAnimation(layoutAnimationController);
recyclerView.getAdapter().notifyDataSetChanged();
recyclerView.scheduleLayoutAnimation();
}
int productId;
#Override
public void onItemClick(int position) {
shareViewModel.setProductIdMutable(brandProductData.getPOPULARPRODUCTS().get(position).getProductId());
fragmentTransaction();
}
#Override
public void onItemClickCategory(int position) {
shareViewModel.setProductIdMutable(brandProductData.getNEWRELEASEPRODUCTS().get(position).getProductId());
fragmentTransaction();
}
#Override
public void onChipItemClick(int position) {
shareViewModel.setProductIdMutable(brandProductData.getHIGHESTPRODUCTS().get(position).getProductId());
fragmentTransaction();
}
#Override
public void onclick(int position) {
shareViewModel.setProductIdMutable(brandProductData.getLOWESTPRODUCTS().get(position).getProductId());
fragmentTransaction();
}
private void fragmentTransaction() {
Bundle bundle = new Bundle();
bundle.putString("BrandProduct", "brand");
PreviewProductFragment previewProductFragment = new PreviewProductFragment();
previewProductFragment.setArguments(bundle);
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction().addToBackStack("");
fragmentTransaction.setCustomAnimations(R.anim.enter_right_to_left, R.anim.exit_right_to_left);
fragmentTransaction.replace(R.id.tabbed_framelayout, previewProductFragment);
fragmentTransaction.commit();
}
}
BrandProfileViewPagerAdapter this is my viewPager Adapter :
public class BrandProfileViewPagerAdapter extends FragmentStatePagerAdapter {
private int tabCount;
public BrandProfileViewPagerAdapter(#NonNull FragmentManager fm, int tabs) {
super(fm, tabs);
this.tabCount=tabs;
}
#NonNull
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
BrandProductFragment brandProductFragment = new BrandProductFragment();
return brandProductFragment;
case 1:
BrandProfileFragment brandProfileFragment= new BrandProfileFragment();
return brandProfileFragment;
default:
return null;
}
}
#Override
public int getCount() {
return tabCount;
}
}
Before :
After :
I want to pass a string value from my adapter class to my fragment. I tried storing the string in a bundle. To retrieve the value i used Bundle b = getArguments(); b.getString("key") the problem is im getting a null pointer exception. Below is the code that saves the string in a bundle. So my question is how can i pass a string value from adapterA to fragmentB.
Thanks in advance.
Adapter.java
public class ToDoRecyclerViewAdapter extends RecyclerView.Adapter<ToDoRecyclerViewAdapter.ViewHolder> {
private Context context;
private List<Aktivnost_> mValues;
private final OnListFragmentInteractionListener mListener;
public ToDoRecyclerViewAdapter td;
public ToDoRecyclerViewAdapter(List<Aktivnost_ > items, Context context, OnListFragmentInteractionListener listener) {
mValues = items;
mListener = listener;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fragment_todo, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.mItem = mValues.get(position);
holder.mContentView.setText(mValues.get(position).getNaziv());
holder.mDateView.setText(mValues.get(position).getDatum());
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (null != mListener) {
mListener.onListFragmentInteraction(holder.mItem);
Intent i = new Intent(context.getApplicationContext(), PodrobnostiActivity.class);
i.putExtra("task_id", mValues.get(position).getId_());
context.getApplicationContext().startActivity(i);
Toast.makeText(v.getContext(), "task - " + mValues.get(position).getId_(), Toast.LENGTH_SHORT).show();
}
}
});
holder.mView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(final View v) {
AlertDialog.Builder adb = new AlertDialog.Builder(v.getContext());
CharSequence meni[] = new CharSequence[] {"DOING", "FINISHED"};
adb.setItems(meni, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if(i == 0) {
Bundle b = new Bundle();
DoingFragment d = new DoingFragment();
mValues.get(i).setStanje("doing");
b.putString("doing", mValues.get(i).getStanje());
d.setArguments(b);
} else {
mValues.get(i).setStanje("koncano");
}
}
});
AlertDialog alertDialog = adb.create();
alertDialog.setCancelable(true);
alertDialog.show();
return true;
}
});
}
#Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mContentView;
public final TextView mDateView;
public long id;
public Aktivnost_ mItem;
public ViewHolder(View view) {
super(view);
mView = view;
this.id = id;
mDateView = (TextView) view.findViewById(R.id.Date);
mContentView = (TextView) view.findViewById(R.id.content);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
And i want to get the value i set in bundle in this fragment.
Fragment.java
public class DoingFragment extends Fragment {
DoingFragmentRecyclerViewAdapter mAdapter;
private OnListFragmentInteractionListener mListener;
public DoingFragment() {
}
#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_doingfragment_list, container, false);
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.list_doing);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL));
mAdapter = new DoingFragmentRecyclerViewAdapter(listAktivnosti(),mListener);
recyclerView.setAdapter(mAdapter);
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnListFragmentInteractionListener) {
mListener = (OnListFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnListFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnListFragmentInteractionListener {
void onListFragmentInteraction1(Aktivnost_ item);
}
AppDatabase db;
public void openDB() {
db = new AppDatabase(getContext());
db.open();
}
Aktivnost_ ak;
List<Aktivnost_> array;
public List<Aktivnost_> listAktivnosti() {
array = new ArrayList<>();
openDB();
Bundle b = getArguments();
Cursor cursor = db.getAllRows(b.getString("doing"));
while(cursor.moveToNext()) {
ak = new Aktivnost_();
ak.setId_(cursor.getLong(cursor.getColumnIndex("_id")));
ak.setNaziv(cursor.getString(cursor.getColumnIndex("naziv")));
ak.setDatum(cursor.getString(cursor.getColumnIndex("datum")));
ak.setFk_projekt(cursor.getInt(cursor.getColumnIndex("fk_projekt")));
ak.setUdeleženci(cursor.getString(cursor.getColumnIndex("udelezenci")));
ak.setStanje(cursor.getString(cursor.getColumnIndex("stanje")));
array.add(ak);
}
return array;
}
}
From the code, I can see you are only setting the Bundle parameters in Fragment object, but not using that fragment object further.
You need to display that fragment object first, then it will reflect into your target fragment.
I am trying to open a url link when I click on a list item in a recyclerview but I keep getting a NullPointerException. I am using a ViewPager, I don't know if this is the cause of the exception, maybe I'm doing something wrong. Please check out my code and logcat below.
This is my adapter:
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.NewsHolder> {
private ArrayList<News> mNews = new ArrayList<>();
private static ClickListener clickListener;
public NewsAdapter(ArrayList<News> news) {
mNews = news;
}
private static String timeConverter(String inputTime) {
long startTime = 0;
SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
simpleDate.setTimeZone(TimeZone.getTimeZone("GMT"));
try {
Date date = simpleDate.parse(inputTime);
startTime = date.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
long currentTime = System.currentTimeMillis();
long end = currentTime - startTime;
long seconds = TimeUnit.MILLISECONDS.toSeconds(end);
long minutes = TimeUnit.SECONDS.toMinutes(seconds);
long hours = TimeUnit.MINUTES.toHours(minutes);
if (minutes > 59) {
return hours + "h";
}else if (seconds > 59) {
return minutes + "m";
}else {
return seconds + "s";
}
}
#Override
public NewsHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_view, parent, false);
return new NewsHolder(view);
}
#Override
public void onBindViewHolder(NewsHolder holder, int position) {
String imagePath = mNews.get(position).getImageUrl();
Picasso.with(holder.mImageView.getContext()).load(imagePath).into(holder.mImageView);
holder.mNewsTextView.setText(mNews.get(position).getNews());
holder.mTimeStampTextView.setText(timeConverter(mNews.get(position).getTime()));
}
#Override
public int getItemCount() {
return mNews.size();
}
// NewsHolder class that extends the ViewHolder
public static class NewsHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView mImageView;
private TextView mNewsTextView;
private TextView mTimeStampTextView;
// Setting the views
public NewsHolder(View itemView) {
super(itemView);
mImageView = (ImageView) itemView.findViewById(R.id.simple_imageView);
mNewsTextView = (TextView) itemView.findViewById(R.id.news_tv);
mTimeStampTextView = (TextView) itemView.findViewById(R.id.time_tv);
}
#Override
public void onClick(View view) {
clickListener.onItemClick(getAdapterPosition(), view);
}
}
public void setOnItemClickListener(ClickListener listener) {
NewsAdapter.clickListener = listener;
}
public interface ClickListener {
void onItemClick(int position, View v);
}
}
This is one of my ViewPager fragments:
public class TechFragment extends Fragment {
private SwipeRefreshLayout mSwipeRefreshLayout;
private TextView mErrorMessage;
private NewsAdapter mNewsAdapter;
ArrayList<News> news;
NetworkInfo info;
// The Loader takes in a bundle
Bundle sourceBundle = new Bundle();
private final String LOG_TAG = MainActivity.class.getSimpleName();
private static final String TECH_NEWS_QUERY_URL = "query";
private static final String TECH_NEWS_SOURCE = "techcrunch";
private static final String TECH_SOURCE_CATEGORY = "latest";
private static final int TECH_NEWS_LOADER = 22;
private RecyclerView mRecyclerView;
public TechFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_news, container, false);
mErrorMessage = (TextView) view.findViewById(R.id.tv_error_message);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view_main);
mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipeRefresh);
getActivity().getSupportLoaderManager().initLoader(TECH_NEWS_LOADER, sourceBundle, new NewsDataLoader());
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
Log.v(LOG_TAG, "Refreshing");
restartLoader();
mSwipeRefreshLayout.setColorSchemeResources(
R.color.colorPrimary,
R.color.colorPrimaryDark);
}
});
return view;
}
private boolean isConnected() {
ConnectivityManager cm = (ConnectivityManager) getActivity()
.getSystemService(CONNECTIVITY_SERVICE);
info = cm.getActiveNetworkInfo();
return info != null && info.isConnectedOrConnecting();
}
private int anyRandomInt(Random random) {
return random.nextInt();
}
private void restartLoader() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
URL techNewsUrl = NetworkUtils.buildUrl(TECH_NEWS_SOURCE, TECH_SOURCE_CATEGORY);
sourceBundle.putString(TECH_NEWS_QUERY_URL, techNewsUrl.toString());
Random random = new Random();
int uniqueId = anyRandomInt(random); //Generates a new ID for each loader call;
LoaderManager loaderManager = getActivity().getSupportLoaderManager();
if (loaderManager.getLoader(TECH_NEWS_LOADER) == null) {
loaderManager.initLoader(uniqueId, sourceBundle, new NewsDataLoader());
} else {
loaderManager.restartLoader(TECH_NEWS_LOADER, sourceBundle, new
NewsDataLoader());
}
}
}, 5000);
mSwipeRefreshLayout.setRefreshing(false);
Log.v(LOG_TAG, "Finished refreshing");
}
private void showErrorScreen() {
mErrorMessage.setVisibility(View.VISIBLE);
mRecyclerView.setVisibility(View.INVISIBLE);
mErrorMessage.setText(getString(R.string.internet_error));
}
public class NewsDataLoader implements LoaderManager.LoaderCallbacks<ArrayList<News>> {
#Override
public Loader<ArrayList<News>> onCreateLoader(int id, final Bundle args) {
if (isConnected()) {
mErrorMessage.setVisibility(View.INVISIBLE);
mRecyclerView.setVisibility(View.VISIBLE);
return new AsyncTaskLoader<ArrayList<News>>(getActivity()) {
ArrayList<News> mNewsData;
#Override
protected void onStartLoading() {
super.onStartLoading();
if (mNewsData != null) {
deliverResult(mNewsData);
} else {
forceLoad();
mSwipeRefreshLayout.setRefreshing(true);
}
}
#Override
public ArrayList<News> loadInBackground() {
try {
ArrayList<News> news = NetworkUtils.parseJSON(TECH_NEWS_SOURCE, TECH_SOURCE_CATEGORY);
return news;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public void deliverResult(ArrayList<News> data) {
mNewsData = data;
super.deliverResult(data);
}
};
} else {
showErrorScreen();
return null;
}
}
#Override
public void onLoadFinished(Loader<ArrayList<News>> loader, final ArrayList<News> data) {
mSwipeRefreshLayout.setRefreshing(false);
if (null == data) {
showErrorScreen();
} else {
mErrorMessage.setVisibility(View.INVISIBLE);
mRecyclerView.setVisibility(View.VISIBLE);
if (news != null) {
news.clear();
news.addAll(data);
mNewsAdapter = new NewsAdapter(news);
mRecyclerView.setAdapter(mNewsAdapter);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
mNewsAdapter.notifyDataSetChanged();
} else {
news = data;
}
}
mNewsAdapter.setOnItemClickListener(new NewsAdapter.ClickListener() {
#Override
public void onItemClick(int position, View v) {
News currentNews = news.get(position);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(currentNews.getUrl()));
if (intent.resolveActivity(getActivity().getPackageManager()) != null){
startActivity(intent);
}
}
});
}
#Override
public void onLoaderReset(Loader<ArrayList<News>> loader) {
}
}
}
And this is my error:
06-13 12:11:38.667 3890-3890/com.ire.blogbot E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.ire.blogbot, PID: 3890
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.ire.blogbot.adapter.NewsAdapter.setOnItemClickListener(com.ire.blogbot.adapter.NewsAdapter$ClickListener)' on a null object reference
at com.ire.blogbot.fragments.TechFragment$NewsDataLoader.onLoadFinished(TechFragment.java:192)
at com.ire.blogbot.fragments.TechFragment$NewsDataLoader.onLoadFinished(TechFragment.java:131)
at android.support.v4.app.LoaderManagerImpl$LoaderInfo.callOnLoadFinished(LoaderManager.java:476)
at android.support.v4.app.LoaderManagerImpl$LoaderInfo.onLoadComplete(LoaderManager.java:444)
at android.support.v4.content.Loader.deliverResult(Loader.java:126)
at com.ire.blogbot.fragments.TechFragment$NewsDataLoader$1.deliverResult(TechFragment.java:164)
at com.ire.blogbot.fragments.TechFragment$NewsDataLoader$1.deliverResult(TechFragment.java:137)
at android.support.v4.content.AsyncTaskLoader.dispatchOnLoadComplete(AsyncTaskLoader.java:252)
at android.support.v4.content.AsyncTaskLoader$LoadTask.onPostExecute(AsyncTaskLoader.java:80)
at android.support.v4.content.ModernAsyncTask.finish(ModernAsyncTask.java:485)
at android.support.v4.content.ModernAsyncTask$InternalHandler.handleMessage(ModernAsyncTask.java:502)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Try this code, it is working
recyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(getActivity(), new RecyclerItemClickListener.OnItemClickListener() {
#Override public void onItemClick(View view, int position) {
// on click
}
})
);
RecyclerItemClickListener Class
public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
private OnItemClickListener mListener;
public interface OnItemClickListener {
public void onItemClick(View view, int position);
}
GestureDetector mGestureDetector;
public RecyclerItemClickListener(Context context, OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
View childView = view.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}}
Move
mNewsAdapter.setOnItemClickListener(new NewsAdapter.ClickListener() {
#Override
public void onItemClick(int position, View v) {
News currentNews = news.get(position);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(currentNews.getUrl()));
if (intent.resolveActivity(getActivity().getPackageManager()) != null){
startActivity(intent);
}
}
});
after
mNewsAdapter = new NewsAdapter(news);
I have a fragment with a list of recipes. But I can't get the onItemClick to work...
I have tried it with onListItemClick but that didn't seem to work either.
My Fragment
public class RecipeBookListViewFragment extends ListFragment implements AdapterView.OnItemClickListener {
private List<Recipe> recipes;
private DataPassListener mCallback;
private ListView recipeList;
public interface DataPassListener{
public void passData(Recipe recipe);
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
RecipeBookActivity.CONTEXT = getActivity().getApplicationContext();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_recipeitem_list, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
fillRecipeBook();
getListView().setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
Recipe recipe = (Recipe) getListAdapter().getItem(position);
final ProgressDialog dialog = ProgressDialog.show(getActivity(), "", "halloooooo...");
mCallback.passData(recipe);
}
#Override
public void onViewCreated(View v, Bundle savedInstanceState){
super.onViewCreated(v,savedInstanceState);
recipeList = getListView();
recipeList.setClickable(true);
}
#Override
public void onAttach(Activity activity){
super.onAttach(activity);
try {
mCallback = (DataPassListener)activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement DataPassListener");
}
}
private void fillRecipeBook(){
final ProgressDialog dialog = ProgressDialog.show(getActivity(), "", "loading...");
RestClient.ApiInterface service = RestClient.getClient();
Call<List<Recipe>> call = service.recipes();
call.enqueue(new Callback<List<Recipe>>() {
#Override
public void onResponse(Response<List<Recipe>> response, Retrofit retrofit) {
dialog.dismiss();
Log.d("MainActivity", "Status Code = " + response.code());
if (response.isSuccess()) {
// request successful (status code 200, 201)
recipes = response.body();
ArrayAdapter<String> adapter = new RecipeListAdapter(getActivity(), recipes);
setListAdapter(adapter);
} else {
// response received but request not successful (like 400,401,403 etc)
//Handle errors
}
}
#Override
public void onFailure(Throwable t) {
Log.d("MainActivity", "GOE KAPOT " + t.getMessage());
dialog.dismiss();
}
});
}
}
my ListView.xml
<?xml version="1.0" encoding="utf-8"?>
<ListView android:id="#android:id/list" android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#FFCC00"
android:dividerHeight="2dp"/>
<TextView android:id="#+id/recipe_title" android:layout_width="match_parent"
android:layout_height="match_parent" android:gravity="left"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"/>
My custom adapter
public class RecipeListAdapter extends ArrayAdapter{
private Context context;
private boolean useList = true;
private List<Recipe> recipes;
public RecipeListAdapter(Context context, List<Recipe> recipes) {
super(context,-1, recipes);
this.context = context;
this.recipes = recipes;
}
private class ViewHolder{
TextView titleText;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
Recipe recipe = (Recipe)getItem(position);
View viewToUse;
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
if(useList){
viewToUse = mInflater.inflate(R.layout.fragment_recipeitem_list, null);
} else {
viewToUse = mInflater.inflate(R.layout.fragment_recipeitem_grid, null);
}
holder = new ViewHolder();
holder.titleText = (TextView)viewToUse.findViewById(R.id.recipe_title);
viewToUse.setTag(holder);
} else {
viewToUse = convertView;
holder = (ViewHolder) viewToUse.getTag();
}
holder.titleText.setText(recipe.getTitle());
return viewToUse;
}
}
my main activity:
public class RecipeBookActivity extends Activity implements DataPassListener {
public static Context CONTEXT;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recipe);
if(findViewById(R.id.recipe_list_fragment) != null){
if (savedInstanceState != null)
return;
RecipeBookListViewFragment recipeBookListViewFragmentFragment = new RecipeBookListViewFragment();
recipeBookListViewFragmentFragment.setArguments(getIntent().getExtras());
getFragmentManager().beginTransaction().add(R.id.recipe_list_fragment,
recipeBookListViewFragmentFragment).commit();
}
}
#Override
public void passData(Recipe recipe){
RecipeFragment recipeFragment = new RecipeFragment();
Bundle args = new Bundle();
args.putSerializable(recipeFragment.DATA_RECEIVE, recipe);
recipeFragment.setArguments(args);
getFragmentManager().beginTransaction()
.replace(R.id.recipe_list_fragment, recipeFragment)
.commit();
}
}
You need to set the onItemClickListener to the ListView before it can register any clicks. Change your onViewCreated code to:
#Override
public void onViewCreated(View v, Bundle savedInstanceState){
super.onViewCreated(v,savedInstanceState);
recipeList = getListView();
recipeList.setOnItemClickListener(this);
}
That way any item clicks on the ListView will be handled in the onItemClick() method that is overidden in the Fragment.
I'm trying to implement Tabs. The Tabs will contain the exact same layout and the same fragment with only one difference - the API URL! (e.g. Trending/Newest).
My Code:
TabFragment
public class TabFragments extends Fragment implements OnPageChangeListener,
OnTabChangeListener {
private TabHost tabHost;
private int currentTab = 0;
private ViewPager viewPager;
private TabFragmentPageAdapter pageAdapter;
private List<Fragment> fragments;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tabhost, null);
tabHost = (TabHost) rootView.findViewById(android.R.id.tabhost);
viewPager = (ViewPager) rootView.findViewById(R.id.viewpager);
viewPager.setOnPageChangeListener(this);
//Create correct fragment
fragments=new ArrayList<>();
fragments.add(new ItemStreamFragment());
fragments.add(new ItemStreamFragment());
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
pageAdapter = new TabFragmentPageAdapter(getChildFragmentManager(),
fragments);
pageAdapter.notifyDataSetChanged();
viewPager.setAdapter(pageAdapter);
setupTabs();
}
private void setupTabs() {
tabHost.setup();
tabHost.addTab(newTab(R.string.tab_1_item));
tabHost.addTab(newTab(R.string.tab_2_item));
for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {
tabHost.getTabWidget().getChildAt(i)
.setBackgroundColor(Color.parseColor("#304c58"));
// tabHost.setBackgroundResource(R.drawable.tab_selector);
final View view = tabHost.getTabWidget().getChildTabViewAt(i);
final View textView = view.findViewById(android.R.id.title);
((TextView) textView).setTextColor(Color.parseColor("#e2ebf0"));
((TextView) textView).setSingleLine(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
tabHost.getTabWidget().getChildAt(i)
.findViewById(android.R.id.icon);
tabHost.getTabWidget().getChildAt(i).getLayoutParams().height = 75;
} else {
if (view != null) {
// reduce height of the tab
view.getLayoutParams().height *= 0.77;
if (textView instanceof TextView) {
((TextView) textView).setGravity(Gravity.CENTER);
textView.getLayoutParams().height = ViewGroup.LayoutParams.MATCH_PARENT;
textView.getLayoutParams().width = ViewGroup.LayoutParams.WRAP_CONTENT;
}
}
}
}
tabHost.setOnTabChangedListener(TabFragments.this);
tabHost.setCurrentTab(currentTab);
}
private TabSpec newTab(int titleId) {
TabSpec tabSpec = tabHost.newTabSpec(getString(titleId));
tabSpec.setIndicator(getString(titleId));
tabSpec.setContent(new TabFactory(getActivity()));
return tabSpec;
}
#Override
public void onPageScrollStateChanged(int position) {
}
#Override
public void onPageScrolled(int position, float arg1, int arg2) {
}
#Override
public void onPageSelected(int position) {
tabHost.setCurrentTab(position);
}
#Override
public void onTabChanged(String tabId) {
currentTab = tabHost.getCurrentTab();
viewPager.setCurrentItem(currentTab);
}
#SuppressWarnings("unused")
private void updateTab() {
switch (currentTab) {
case 0:
ItemStreamFragment login = (ItemStreamFragment) fragments.get(currentTab);
break;
case 1:
ItemStreamFragment register = (ItemStreamFragment) fragments
.get(currentTab);
break;
}
}
class TabFactory implements TabContentFactory {
private final Context context;
public TabFactory(Context context) {
this.context = context;
}
#Override
public View createTabContent(String tag) {
View v = new View(context);
v.setMinimumHeight(0);
v.setMinimumWidth(0);
return v;
}
}
}
TabFragmentPageAdapter
public class TabFragmentPageAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public TabFragmentPageAdapter(FragmentManager fm, List<Fragment> fragments
) {
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int position) {
Fragment fragment = fragments.get(position);
Bundle args = new Bundle();
args.putInt("position", position);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return fragments.size();
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
And finally ItemStreamFragment
public class ItemStreamFragment extends Fragment {
private String mApiUrl = "http://api.eese.com:8080/ICDS_API/v1/reco.getNewest/?page=0&limit=13×tamp=2015-07-02+10%3A34%3A07&lang_key=en";
private final String mImages = "http://d30q95ofpjr96w.cloudfront.net/";
private ItemStream[] mObjectItem;
private int mPosition = 0;
public ItemStreamAdapter mAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getArguments();
if (bundle != null) {
mPosition = bundle.getInt("position", 0);
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_itemstream, container, false);
view.setId(mPosition);
getStream(mPosition);
return view;
}
private void getStream(int position) {
switchUrl(position);
new GetRequestTask(new OnTaskCompleted() {
#Override
public void onTaskCompleted(String result) {
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonResults = jsonObject.getJSONArray("results");
final int resultLength = jsonResults.length();
mObjectItem = new ItemStream[resultLength];
for (int i = 0; i < resultLength; i++) {
JSONObject item = jsonResults.getJSONObject(i);
mObjectItem[i] = new ItemStream(item.getInt("id"), item.getString("title"), mImages + "" + item.getString("thumbnail") + ".374x210." + item.getString("thumbnail_type"));
}
if (getActivity() != null) {
mAdapter = new ItemStreamAdapter(getActivity(), R.layout.list_itemstream, mObjectItem);
ListView scrollView = (ListView) getActivity().findViewById(R.id.itemstream_trend);
scrollView.setAdapter(mAdapter);
}
} catch (Exception ex) {
}
}
}).execute(mApiUrl);
}
//Needs to be tuned
private void switchUrl(int position) {
switch (position) {
case 0:
mApiUrl = "http://api.eese.com:8080/ICDS_API/v1/reco.getTrending/?page=0&limit=13×tamp=2015-07-02+10%3A34%3A07&lang_key=en";
break;
case 1:
mApiUrl = "http://api.eese.com:8080/ICDS_API/v1/reco.getNewest/?page=0&limit=13×tamp=2015-07-02+10%3A34%3A07&lang_key=en";
break;
}
}
}
And here you see what happens:
(Sry for the overlay :) )
The thing is that the first Tab is loaded with data but the second tab stays empty (it shouldn't be empty though). Not sure what is wrong here. Would be cool if you can point me in the right direction :)
For using Tabs in material design you should use TabLayout from design support library. Here is the tutorial from where you can learn this new approach.
As far as loading fragment is concern, you second fragment will be loaded with first this is complete different discussion with viewpager, so you need to have different url for each fragment and don't create fragment using new Operator. Instead create static getInstance() in Fragment class and pass the url from there and using Fragment#setArgument(Bundle) get new Fragment instance. When fragment view is created i.e in onViewCreated(...) get arguments from bundle in your case String url and call webservice which will return the respective response.
Fixed the problem:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_itemstream, container, false);
view.setId(mPosition);
getStream(mPosition,view);
return view;
}
private void getStream(int position, final View view) {
switchUrl(position);
new GetRequestTask(new OnTaskCompleted() {
#Override
public void onTaskCompleted(String result) {
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonResults = jsonObject.getJSONArray("results");
final int resultLength = jsonResults.length();
mObjectItem = new ItemStream[resultLength];
for (int i = 0; i < resultLength; i++) {
JSONObject item = jsonResults.getJSONObject(i);
mObjectItem[i] = new ItemStream(item.getInt("id"), item.getString("title"), mImages + "" + item.getString("thumbnail") + ".374x210." + item.getString("thumbnail_type"));
}
if (getActivity() != null) {
mAdapter = new ItemStreamAdapter(getActivity(), R.layout.list_itemstream, mObjectItem);
ListView scrollView = (ListView) view.findViewById(R.id.itemstream_trend);
scrollView.setAdapter(mAdapter);
}
} catch (Exception ex) {
}
}
}).execute(mApiUrl);
}
Just added view to the method getStream. Now it is working! What do you think about this solution?