how to place Cardview in a fragment - java

Good Day,
i have an app, with a Main activity, Fragment and Tabbed Fragments. i am trying to use Cardview to display a list of posts on my Allposts fragment. But when i run it, nothing shows.
MainActivity.java
package com.example.stephan.regnotifier;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import com.example.stephan.regnotifier.activity.AboutFragment;
import com.example.stephan.regnotifier.activity.PostsFragment;
import com.example.stephan.regnotifier.activity.SettingsFragment;
import com.example.stephan.regnotifier.activity.TabFragment;
import com.example.stephan.regnotifier.activity.TimetableFragment;
public class MainActivity extends AppCompatActivity{
DrawerLayout mDrawerLayout;
NavigationView mNavigationView;
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/**
*Setup the DrawerLayout and NavigationView
*/
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mNavigationView = (NavigationView) findViewById(R.id.shitstuff) ;
/**
* Lets inflate the very first fragment
* Here , we are inflating the TabFragment as the first Fragment
*/
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView,new TabFragment()).commit();
/**
* Setup click events on the Navigation View Items.
*/
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
mDrawerLayout.closeDrawers();
if (menuItem.getItemId() == R.id.nav_item_timetable) {
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.containerView,new TimetableFragment()).commit();
}
if (menuItem.getItemId() == R.id.nav_item_post) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView,new TabFragment()).commit();
}
if (menuItem.getItemId() == R.id.nav_item_profile) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView,new PostsFragment()).commit();
}
if (menuItem.getItemId() == R.id.nav_item_settings) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView,new SettingsFragment()).commit();
}
if (menuItem.getItemId() == R.id.nav_item_about) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView,new AboutFragment()).commit();
}
if (menuItem.getItemId() == R.id.nav_item_logout) {
Intent logout = new Intent(MainActivity.this, LoginActivity.class);
startActivity(logout);
}
return false;
}
});
/**
* Setup Drawer Toggle of the Toolbar
*/
android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this,mDrawerLayout, toolbar,R.string.app_name,
R.string.app_name);
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
}
}
AllpostsFragment.java
package com.example.stephan.regnotifier.activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.CardView;
import android.support.v7.widget.DefaultItemAnimator;
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 com.example.stephan.regnotifier.R;
/**
* A simple {#link Fragment} subclass.
*/
public class AllpostsFragment extends Fragment {
public AllpostsFragment() {
// Required empty public constructor
}
CardView mCardView;
RecyclerView mRecyclerView;
RecyclerView.LayoutManager mLayoutManager;
RecyclerView.Adapter mAdapter;
Context context;
public static AllpostsFragment newInstance() {
AllpostsFragment fragment = new AllpostsFragment();
fragment.setRetainInstance(true);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_allposts, container, false);
RecyclerView rv = (RecyclerView)v.findViewById(R.id.cardList);
mLayoutManager = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);
rv.setLayoutManager(mLayoutManager);
rv.setItemAnimator(new DefaultItemAnimator());
rv.setHasFixedSize(true);
return v;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
}
PostList.java
package com.example.stephan.regnotifier.model;
/**
* Created by StephAn on 18-Feb-16.
*/
public class Posts_list {
private String mName;
private int mThumbnail;
public String getName() {
return mName;
}
public void setName(String name) {
this.mName = name;
}
public int getThumbnail() {
return mThumbnail;
}
public void setThumbnail(int thumbnail) {
this.mThumbnail = thumbnail;
}
}
CardAdapter.java
package com.example.stephan.regnotifier.adapter;
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.example.stephan.regnotifier.R;
import com.example.stephan.regnotifier.model.Posts_list;
import java.util.ArrayList;
import java.util.List;
/**
* Created by StephAn on 18-Feb-16.
*/
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.CardViewHolder>{
List<Posts_list> pItems;
public CardAdapter() {
super();
pItems = new ArrayList<Posts_list>();
Posts_list posts_list = new Posts_list();
posts_list.setName("The Amazing Spider-Man 2");
posts_list.setThumbnail(R.drawable.sample);
pItems.add(posts_list);
posts_list = new Posts_list();
posts_list.setName("X-men: Days of Future Past");
posts_list.setThumbnail(R.drawable.sample);
pItems.add(posts_list);
posts_list = new Posts_list();
posts_list.setName("The Hunger Game");
posts_list.setThumbnail(R.drawable.sample);
pItems.add(posts_list);
posts_list = new Posts_list();
posts_list.setName("Guardians of the Galaxy");
posts_list.setThumbnail(R.drawable.sample);
pItems.add(posts_list);
posts_list = new Posts_list();
posts_list.setName("Maleficent");
posts_list.setThumbnail(R.drawable.sample);
pItems.add(posts_list);
posts_list = new Posts_list();
posts_list.setName("How to Train Your Dragon 2");
posts_list.setThumbnail(R.drawable.sample);
pItems.add(posts_list);
posts_list = new Posts_list();
posts_list.setName("What If");
posts_list.setThumbnail(R.drawable.sample);
pItems.add(posts_list);
}
#Override
public CardViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.card_view_layout, viewGroup, false);
CardViewHolder viewHolder = new CardViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(CardViewHolder cardViewHolder, int i) {
Posts_list posts_list = pItems.get(i);
cardViewHolder.tvMovie.setText(posts_list.getName());
cardViewHolder.imgThumbnail.setImageResource(posts_list.getThumbnail());
}
#Override
public int getItemCount() {
return pItems.size();
}
class CardViewHolder extends RecyclerView.ViewHolder{
public ImageView imgThumbnail;
public TextView tvMovie;
public CardViewHolder(View itemView) {
super(itemView);
imgThumbnail = (ImageView)itemView.findViewById(R.id.img_thumbnail);
tvMovie = (TextView)itemView.findViewById(R.id.tv_movie);
}
}
}
fragment_allpost.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MyActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/cardList"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</RelativeLayout>
card_view_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.CardView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
card_view:contentPadding="#dimen/activity_horizontal_margin"
card_view:cardCornerRadius="3dp">
<ImageView
android:id="#+id/img_thumbnail"
android:layout_width="fill_parent"
android:layout_height="150dp" />
<TextView
android:id="#+id/tv_movie"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:layout_gravity="bottom"
android:gravity="center_vertical"
android:background="#757575"
android:alpha="0.8"
android:textSize="#dimen/abc_text_size_headline_material"
android:text="Test"/>
</android.support.v7.widget.CardView>
</LinearLayout>

Related

Null Pointer on RecyclerView

I am getting a null pointer exception on the following statement within my recyclersetup method.
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
It is due to the following statement not setting a pointer to recyclerView in the previous statement which is
recyclerView = getView().findViewById(R.id.check_in_recent_row);
I cannot determine why I am not getting the recyclerView pointer established via this statement. the ID for the data is correct. What am I missing?
This is the entire fragment code
CheckInRecentList.java
package com.example.checkingin;
import android.content.Context;
import android.net.Uri;
import android.nfc.Tag;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelProvider.Factory;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import java.util.List;
import static androidx.constraintlayout.widget.Constraints.TAG;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link CheckInRecentList.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link CheckInRecentList#newInstance} factory method to
* create an instance of this fragment.
*/
public class CheckInRecentList extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private RecyclerView recyclerView;
private RecyclerView.Adapter checkInListAdapter;
//private RecyclerView.LayoutManager layoutManager;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private MainViewModel mViewModel;
private CheckInListAdapter adapter;
private MainViewModelProviderFactory viewModelFactory;
private TextView checkInLastDateTime;
private TextView checkInTitle;
private TextView checkInDestinationName;
private TextView checkInComments;
private OnFragmentInteractionListener mListener;
public CheckInRecentList() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment CheckInRecentList.
*/
// TODO: Rename and change types and number of parameters
public static CheckInRecentList newInstance(String param1, String param2) {
CheckInRecentList fragment = new CheckInRecentList();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "onCreate: On Create");
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
// These were originally set up from the recycler view add to the fragment
// recyclerView = findViewById(R.id.check_in_recent_recycler_view);
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
//recyclerView.setHasFixedSize(true);
/*
// use a linear layout manager
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
*/
// specify an adapter (see also next example)
//checkInListAdapter = new CheckInListAdapter();
// recyclerView.setAdapter(checkInListAdapter);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mViewModel = new ViewModelProvider(this, viewModelFactory).get(MainViewModel.class);
Log.i(TAG, "onCreateView: On Create View");
// Inflate the layout for this fragment
return inflater.inflate(R.layout.recycler_view_item, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
Log.i(TAG, "onButtonPressed: ");
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
Log.i(TAG, "onAttach: OnAttach");
viewModelFactory = new MainViewModelProviderFactory(context.getApplicationContext());
mViewModel = new ViewModelProvider(this, viewModelFactory).get(MainViewModel.class);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
Log.i(TAG,"OnAttach completed");
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.i(TAG, "onActivityCreated: On Activity Created");
mViewModel = new ViewModelProvider(this, viewModelFactory).get(MainViewModel.class);
checkInLastDateTime = getView().findViewById(R.id.checkInLastDateTime);
checkInTitle = getView().findViewById(R.id.checkInTitle);
checkInDestinationName = getView().findViewById(R.id.checkInDestinationName);
checkInComments = getView().findViewById(R.id.checkInComments);
recyclerSetup();
Log.i(TAG,"OnActivityCreated: Recycler SetUp");
//listenerSetup();
//Log.i(TAG, "onActivityCreated: Listener SetUp");
observerSetup();
Log.i(TAG, "onActivityCreated: Observer SetUp");
}
#Override
public void onDetach() {
super.onDetach();
Log.i(TAG, "onDetach: ");
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
private void clearFields() {
checkInLastDateTime.setText("");
checkInDestinationName.setText("");
checkInTitle.setText("");
checkInComments.setText("");
}
private void listenerSetup() {
ImageButton editCheckInButton = getView().findViewById(R.id.checkInEditButton);
ImageButton resendCheckInButton = getView().findViewById(R.id.checkInResendButton);
mViewModel = new ViewModelProvider(this, viewModelFactory).get(MainViewModel.class);
Log.i(TAG, "listenerSetup: ");
editCheckInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//put in edit check in logic
}
});
resendCheckInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//put in resend logic
}
});
}
private void observerSetup() {
Log.i(TAG, "observerSetup:");
if(mViewModel.getAllCheckIn() != null)
mViewModel.getAllCheckIn().observe(getViewLifecycleOwner(), new Observer<List<CheckInTable>>(){
#Override
public void onChanged(#Nullable final List<CheckInTable> allCheckIn) {
adapter.setCheckInList(allCheckIn);
}
});
mViewModel.getAllCheckIn().observe(getViewLifecycleOwner(), new Observer<List<CheckInTable>>() {
#Override
public void onChanged(#Nullable final List<CheckInTable> allCheckIn) {
if (allCheckIn.size() > 0) {
Log.i(TAG, "onChanged: all check in size greater than zero");
checkInLastDateTime.setText(allCheckIn.get(0).getCheckInLastDateTime());
Log.i(TAG, "onChanged: running again");
checkInDestinationName.setText(allCheckIn.get(0).getCheckInDestinationName());
checkInTitle.setText(allCheckIn.get(0).getCheckInTitle());
checkInComments.setText(allCheckIn.get(0).getCheckInComments());
} else {
checkInLastDateTime.setText("None Found");
}
}
});
}
private void recyclerSetup() {
Log.i(TAG, "recyclerSetup: ");
adapter = new CheckInListAdapter(R.layout.fragment_check_in_recent_list);
RecyclerView recyclerView = getView().findViewById(R.id.check_in_recent_recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(adapter);
//recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
}
}
The following are the xml files for the fragment
fragment_check_in_recent_list.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".CheckInRecentList">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/check_in_recent_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:listitem="#layout/recycler_view_item"/>
</FrameLayout>
and recycler_view_item.xml
<?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="horizontal"
android:padding="8dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TableLayout
android:id="#+id/check_in_recent_row"
android:layout_width="389dp"
android:layout_height="match_parent"
android:layout_gravity="center"
android:padding="30dp">
<TableRow
android:layout_width="346dp"
android:layout_height="match_parent">
<TextView
android:id="#+id/checkInLastDateTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"/>
<TextView
android:id="#+id/checkInTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<TextView
android:id="#+id/checkInDestinationName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<ImageButton
android:id="#+id/checkInEditButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#android:drawable/ic_menu_edit"
android:tooltipText="Edit Check In" />
<ImageButton
android:id="#+id/checkInResendButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#android:drawable/ic_menu_share"
android:tooltipText="Resend Check In" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/checkInComments"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</TableRow>
</TableLayout>
</LinearLayout>
CheckInListAdapter
package com.example.checkingin;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.app.Activity;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
import static androidx.constraintlayout.widget.Constraints.TAG;
public class CheckInListAdapter extends RecyclerView.Adapter<CheckInListAdapter.ViewHolder>{
private int checkInListLayout;
private List<CheckInTable> checkInList;
public CheckInListAdapter(int layoutId) {
checkInListLayout = layoutId;
}
public void setCheckInList(List<CheckInTable> allCheckIn) {
checkInList = allCheckIn;
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return checkInList == null ? 0 : checkInList.size();
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.i(TAG, "onCreateViewHolder: ");
View view = LayoutInflater.from(
parent.getContext()).inflate(checkInListLayout, parent, false);
ViewHolder checkInListViewHolder = new ViewHolder(view);
return checkInListViewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int listPosition) {
TextView checkInLastDateTime = holder.checkInLastDateTime;
TextView checkInTitle = holder.checkInTitle;
TextView checkInDestinationName = holder.checkInDestinationName;
TextView checkInComments = holder.checkInComments;
ImageView checkInEditButton = holder.checkInEditButton;
ImageView checkInResendButton = holder.checkInResendButton;
Log.i(TAG, "onBindViewHolder: ");
checkInLastDateTime.setText(checkInList.get(listPosition).getCheckInLastDateTime());
checkInTitle.setText(checkInList.get(listPosition).getCheckInTitle());
checkInDestinationName.setText(checkInList.get(listPosition).getCheckInDestinationName());
checkInComments.setText(checkInList.get(listPosition).getCheckInComments());
holder.checkInEditButton.setImageResource(R.drawable.ic_menu_edit);
holder.checkInResendButton.setImageResource(R.drawable.ic_menu_share);
ImageButton editCheckInButton = checkInEditButton.findViewById(R.id.checkInEditButton);
ImageButton resendCheckInButton = checkInResendButton.findViewById(R.id.checkInResendButton);
editCheckInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//put in edit check in logic
}
}
);
resendCheckInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//put in resend logic
}
});
}
static class ViewHolder extends RecyclerView.ViewHolder {
TextView checkInLastDateTime;
TextView checkInTitle;
TextView checkInDestinationName;
TextView checkInComments;
ImageView checkInEditButton;
ImageView checkInResendButton;
ViewHolder(View itemView) {
super(itemView);
Log.i(TAG, "ViewHolder: ");
checkInLastDateTime = itemView.findViewById(R.id.checkInLastDateTime);
checkInTitle = itemView.findViewById(R.id.checkInTitle);
checkInDestinationName = itemView.findViewById(R.id.checkInDestinationName);
checkInComments = itemView.findViewById(R.id.checkInComments);
checkInEditButton = itemView.findViewById(R.id.checkInEditButton);
checkInResendButton = itemView.findViewById(R.id.checkInResendButton);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
}
}
Your RecyclerView's ID is check_in_recent_recycler_view. Your findViewById call is using check_in_recent_row. These need to match.

why my recyclerview doesn't show data in fragment?

i have created the online wallpaper application and i used to activity for my app and i use volley and glide for my app but when i use bottom navigation drawer , activity is not useful .
after that i use fragment but now when i run application my recyclerview doesn't show anything
MainFragment.java:
package ir.zooding.wallpaper.activity;
import android.Manifest;
import android.app.ProgressDialog;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
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.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import ir.zooding.wallpaper.R;
import ir.zooding.wallpaper.adapter.GalleryAdapter;
import ir.zooding.wallpaper.app.AppController;
import ir.zooding.wallpaper.model.Image;
import ir.zooding.wallpaper.receiver.ConnectivityReceiver;
public class MainFragment extends Fragment implements ConnectivityReceiver.ConnectivityReceiverListener {
RecyclerView recycler_view;
static final String url="";
ArrayList<Image> images;
GalleryAdapter mAdapter;
ProgressDialog pd;
View v;
public static MainFragment newInstance() {
MainFragment fragment = new MainFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_main, container, false);
Toolbar toolbar=(Toolbar)v.findViewById(R.id.toolbar);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
recycler_view=(RecyclerView) v.findViewById(R.id.recycler_view);
pd=new ProgressDialog(getActivity());
pd.setCancelable(false);
images=new ArrayList<>();
mAdapter=new GalleryAdapter(getActivity().getApplicationContext(),images);
RecyclerView.LayoutManager mLayoutManager=new GridLayoutManager(getActivity().getApplicationContext(),2);
recycler_view.setLayoutManager(mLayoutManager);
recycler_view.setAdapter(mAdapter);
Log.i("LOG:","stop 1");
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
1);
recycler_view.addOnItemTouchListener(new GalleryAdapter.RecyclerTouchListener(getActivity().getApplicationContext(),recycler_view, new GalleryAdapter.ClickListener() {
#Override
public void onClick(View view, int position) {
Bundle bundle=new Bundle();
bundle.putSerializable("images",images);
bundle.putInt("position",position);
//Log.i("LOG:",""+position);
// FragmentTransaction ft=getFragmentManager().beginTransaction();
android.app.FragmentTransaction ft=getActivity().getFragmentManager().beginTransaction();
SlideshowDialogFragment newFragment=SlideshowDialogFragment.newInstance();
newFragment.setArguments(bundle);
newFragment.show(ft,"slideshow");
}
#Override
public void onLongClick(View view, int position) {
}
}));
checkConnection();
fetchImages();
return inflater.inflate(R.layout.fragment_main, container, false);
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(getActivity(), "دسترسی به حافظه داخلی لغو شد!!!", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
public void fetchImages()
{
pd.setMessage("در حال بارگزاری ...");
pd.show();
StringRequest req = new StringRequest(url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("", response.toString());
pd.dismiss();
images.clear();
try {
JSONObject object = new JSONObject(response);
JSONArray dataArray = object.getJSONArray("data");
for (int i = 0; i < dataArray.length(); i++) {
JSONObject dataObject = dataArray.getJSONObject(i);
Image image = new Image();
image.setName_client(dataObject.getString("name_client"));
image.setName(dataObject.getString("name"));
// JSONObject url = object.getJSONObject("url");
image.setSmall(dataObject.getString("small"));
image.setOriginal(dataObject.getString("orginal"));
image.setTimestamp(dataObject.getString("timestamp"));
images.add(image);
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.i("LOG:","stop 2");
mAdapter.notifyDataSetChanged();
Log.i("LOG:","stop 3");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("", "Error: " + error.getMessage());
pd.dismiss();
}
});
AppController.getmInstance().addToRequsetQueue(req);
}
// Method to manually check connection status
private void checkConnection() {
boolean isConnected = ConnectivityReceiver.isConnected();
showSnack(isConnected);
}
// Showing the status in Snackbar
private void showSnack(boolean isConnected) {
String message ="";
//View parentLayout = v.findViewById(android.R.id.content);
RelativeLayout parentLayout = (RelativeLayout)v.findViewById(R.id.mroot);
if (!isConnected) {
message = "اتصال شما به اینترنت برقرار نیست!";
Snackbar snackbar = Snackbar
.make(parentLayout, message, Snackbar.LENGTH_LONG)
.setAction("بررسی مجدد", new View.OnClickListener() {
#Override
public void onClick(View view) {
fetchImages();
checkConnection();
}
});
snackbar.setActionTextColor(Color.RED);
snackbar.setActionTextColor(Color.parseColor("#e62d3f"));
View sbView = snackbar.getView();
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.parseColor("#FFC107"));
snackbar.setDuration(8000);
snackbar.show();
}
}
#Override
public void onResume() {
super.onResume();
// register connection status listener
AppController.getmInstance().setConnectivityListener(this);
}
/**
* Callback will be triggered when there is change in
* network connection
*/
#Override
public void onNetworkConnectionChanged(boolean isConnected) {
showSnack(isConnected);
}
}
GalleryAdapter.java:
package ir.zooding.wallpaper.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import java.util.List;
import ir.zooding.wallpaper.R;
import ir.zooding.wallpaper.model.Image;
import static android.R.animator.fade_in;
public class GalleryAdapter extends RecyclerView.Adapter<GalleryAdapter.MyViewHolder> {
List<Image> images;
Context mContext;
public GalleryAdapter (Context context,List<Image> images){
this.images = images;
mContext = context;
}
#Override
public GalleryAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.gallery_thumbnail,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(GalleryAdapter.MyViewHolder holder, int position) {
Image image = images.get(position);
Glide.with(mContext).load(image.getSmall())
.thumbnail(0.5f)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.placeholder(R.drawable.loading)
.fitCenter()
.into(holder.thumbnail);
}
#Override
public int getItemCount() {
return images.size();
}
public interface ClickListener{
void onClick (View view,int position);
void onLongClick (View view,int position);
}
public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener{
GalleryAdapter.ClickListener clickListener;
GestureDetector gestureDetector;
public RecyclerTouchListener(Context context,final RecyclerView recyclerView,final GalleryAdapter.ClickListener clickListener){
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context,new GestureDetector.SimpleOnGestureListener(){
#Override
public boolean onSingleTapUp(MotionEvent e){
return true;
}
#Override
public void onLongPress(MotionEvent e){
View child = recyclerView.findChildViewUnder(e.getX(),e.getY());
if(child != null && clickListener != null){
clickListener.onLongClick(child,recyclerView.getChildPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(),e.getY());
if(child != null && clickListener != null&& gestureDetector.onTouchEvent(e)){
clickListener.onClick(child,rv.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
public class MyViewHolder extends RecyclerView.ViewHolder{
ImageView thumbnail;
public MyViewHolder(View view) {
super(view);
thumbnail =(ImageView) view.findViewById(R.id.thumbnail);
}
}
}
MainActivity.java:
package ir.zooding.wallpaper.activity;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import ir.adad.client.Adad;
import ir.zooding.wallpaper.R;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Adad.initialize(getApplicationContext());
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
BottomNavigationView bottomNavigationView = (BottomNavigationView)
findViewById(R.id.navigation);
bottomNavigationView.setOnNavigationItemSelectedListener
(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.action_item1:
selectedFragment = MainFragment.newInstance();
break;
case R.id.action_item2:
selectedFragment = CategoryFragment.newInstance();
break;
case R.id.action_item3:
selectedFragment = InfoFragment.newInstance();
break;
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_layout, selectedFragment);
transaction.commit();
return true;
}
});
//Manually displaying the first fragment - one time only
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_layout, MainFragment.newInstance());
transaction.commit();
//Used to select an item programmatically
//bottomNavigationView.getMenu().getItem(2).setChecked(true);
}
}
fragment_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<RelativeLayout
android:id="#+id/mroot"
android:layout_width="match_parent"
android:layout_height="match_parent">
</RelativeLayout>
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
/>
</android.support.design.widget.AppBarLayout>
<include
android:id="#+id/include"
layout="#layout/content_main"/>
content_main.xml:
<?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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingTop="?attr/actionBarSize">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:scrollbars="vertical"/>
There are Contexts considerations you need to make throught your code. You may be using the wrong Contexts example very big Contexts. For example from what I can see fast one of it is this line in MainFragment.java:
mAdapter=new GalleryAdapter(getActivity().getApplicationContext(),images);
You have passed the application context while you need just Context from Activity. So change that to:
mAdapter=new GalleryAdapter(getActivity(),images); // remove the method getApplicationContext
Try doing that if it will work or else lets try finding more code that may bring a problem.

connecting parse api to android swipe layout

I'm doing a project using Android swipe layout. I'm getting problem when calling a datas from parse server to swiped tabs.
I'm getting this error when I'm calling a list fragment inside a fragment
below is my fragment class
please check
i updated code but some errors showing please check below screenshot
enter image description here
this error comes
import android.app.ListActivity;
import android.app.ListFragment;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import java.util.ArrayList;
import java.util.List;
public class IndividualsFragment extends ListFragment implements FindCallback<ParseObject> {
private List<ParseObject> mOrganization = new ArrayList<ParseObject>();
#Override
public void onViewCreated(View view, Bundle b) {
super.onViewCreated(view, b);
CustomAdaptor adaptor = new CustomAdaptor(getActivity(), mOrganization);
setListAdapter(adaptor);
// This is like calling fetchList()
ParseQuery.getQuery("Organization").findInBackground(this);
}
/**
* This is needed by implementing the callback on the class
**/
#Override
public void done(List<ParseObject> scoreList, ParseException e) {
if (e == null) {
Log.d("score", "Retrieved " + scoreList.size() + " Organization");
mOrganization.clear();
mOrganization.addAll(scoreList);
getListAdapter().notifyDataSetChanged();
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
}
MainActivity.class
public class MainActivity extends AppCompatActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
Parse.initialize(new Parse.Configuration.Builder(this)
.applicationId("my-app-id")
.server("severn-name")
.build()
);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position) {
case 0:
Individuals t1 = new Individuals();
return t1;
case 1:
Events t2 = new Events();
return t2;
case 2:
Members t3 = new Members();
return t3;
}
return fragment;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "INdividuals";
case 1:
return "Events";
case 2:
return "Members";
}
return null;
}
}
}
This is where I call parse data.
OrganizationActivity.class
public class OrganizationActivity extends ListActivity {
protected List<ParseObject> mOrganization;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_organization);
fetcAndList();
}
void fetcAndList() {
ParseQuery<ParseObject> query = ParseQuery.getQuery("Organization");
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> scoreList, ParseException e) {
if (e == null) {
Log.d("score", "Retrieved " + scoreList.size() + " Organization");
mOrganization = scoreList;
CustomAdaptor adaptor = new CustomAdaptor(getListView().getContext(), mOrganization);
setListAdapter(adaptor);
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
});
}
public void onCreate() { }
}
This is tab1
Individuals.java
import android.database.DataSetObserver;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import java.util.List;
/**
* Created by faizal on 1/17/17.
*/
public class Individuals extends Fragment implements ListAdapter {
public class IndividualsActivity extends Fragment {
ListView listview;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
OrganizationActivity.fetcAndList();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_organization, container, false);
listview = (ListView)v.findViewById(R.id.list);
super.onCreate(savedInstanceState);
return v;
}
}
I have created 5 xml files. This was automatically created when creating the Android Studio project.
activity_main.xml
This is list view xml
activity_organization.xml
<?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:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin">
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
</ListView>
</LinearLayout>
This is tab1.xml
This is the first tab , here I call the fields of list view.
t1.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="cmcom.com.fbcapp.swipe_new.MainActivity$PlaceholderFragment">
<ImageView
android:id="#+id/logo"
android:layout_gravity="left"
android:layout_height="80dp"
android:layout_width="80dp"
android:padding="5dp"
android:paddingLeft="5dp"
android:paddingEnd="5dp"
android:paddingBottom="5dp"
android:paddingRight="5dp"
android:paddingStart="5dp"
android:paddingTop="5dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="12dp"
android:layout_marginStart="12dp"
android:layout_marginTop="14dp">
</ImageView>
<TextView
android:id="#+id/name"
android:text="Name"
android:layout_width="204dp"
android:layout_height="wrap_content"
android:layout_below="#+id/user"
android:layout_alignLeft="#+id/user"
android:layout_alignStart="#+id/user"
android:layout_marginTop="13dp" />
<TextView
android:id="#+id/user"
android:text="Username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="17dp"
android:layout_marginStart="17dp"
android:layout_alignTop="#+id/logo"
android:layout_toRightOf="#+id/logo"
android:layout_toEndOf="#+id/logo" />
</RelativeLayout>
I tried many times but failed to load parse data inside the tab fragments
if anyone know please help me thank you.
Your ListView is not at all attached to the swipe views. Plus, it's an activity. You need to swipe between Fragments. So move the Parse code into a Fragment with a ListView
And a Fragment is not an Adapter, so you need to implement nothing
public class Individuals extends Fragment { // No implements needed
// Code
}
Then setAdapter is not a method of the Fragment class, so you have to use the method of the ListView itself or use a ListFragment
Here's an example of a ListFragment
(code untested)
public class IndividualsFragment
extends android.support.v4.app.ListFragment
implements FindCallback<ParseObject> {
private List<ParseObject> mOrganization = new ArrayList<ParseObject>();
#Override
public void onViewCreated(View view, Bundle b) {
super.onViewCreated(view, b);
CustomAdaptor adaptor = new CustomAdaptor(getActivity(), mOrganization);
setListAdapter(adaptor);
// This is like calling fetchList()
ParseQuery.getQuery("Organization").findInBackground(this);
}
/**
* This is needed by implementing the callback on the class
**/
#Override
public void done(List<ParseObject> scoreList, ParseException e) {
if (e == null) {
Log.d("score", "Retrieved " + scoreList.size() + " Organization");
mOrganization.clear();
mOrganization.addAll(scoreList);
((CustomAdaptor) getListAdapter()).notifyDataSetChanged();
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
}
you may need to call back listview in
OrganizationActivity.class

RecyclerView error: No adapter attached; skipping layout

When I try to add RecyclerView in the sample application, I get an error E/RecyclerView: No adapter attached; skipping layout.
Because of this, the data which is successfully retrieved from my server does not appear on the screen (empty)
This in my code
MainActivity
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import page.DefaultFragment;
import page.HomeFragment;
import page.ProfileFragment;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private static final String TAG = MainActivity.class.getSimpleName();
private final static String API_KEY = "7e8f60e325cd06e164799af1e317d7a7";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_test);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
Fragment fragment = null;
fragment = new DefaultFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.root, fragment);
fragmentTransaction.commit();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
Fragment fragment = null;
String title = getString(R.string.app_name);
if (id == R.id.nav_camera) {
fragment = new HomeFragment();
title = "Home";
} else if (id == R.id.nav_gallery) {
fragment = new ProfileFragment();
title = "Profile";
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.root, fragment);
fragmentTransaction.commit();
getSupportActionBar().setTitle(title);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void showToast(String output){
Toast.makeText(this.getBaseContext(), output, Toast.LENGTH_SHORT).show();
}
}
My Fragment code
package page;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.transvision.bertho.transvisiondashboardapp.R;
import java.util.List;
import adapter.ChannelAdapter;
import model.Channel;
import model.ChannelResponse;
import rest.ApiClient;
import rest.ApiInterface;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class HomeFragment extends Fragment {
private RecyclerView recyclerView;
private static final String TAG = HomeFragment.class.getSimpleName();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.movies_recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
getChannelData();
// Inflate the layout for this fragment
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
public void getChannelData() {
ApiInterface apiService = ApiClient.getChannel().create(ApiInterface.class);
Call<ChannelResponse> call = apiService.getItems();
call.enqueue(new Callback<ChannelResponse>() {
#Override
public void onResponse(Call<ChannelResponse> call, Response<ChannelResponse> response) {
int statusCode = response.code();
List<Channel> channel = response.body().getItems();
recyclerView.setAdapter(new ChannelAdapter(channel, R.layout.list_channel, getActivity()));
}
#Override
public void onFailure(Call<ChannelResponse> call, Throwable t) {
// Log error here since request failed
Log.e(TAG, t.toString());
showToast("CONNECTION ERROR");
}
});
}
public void showToast(String output){
Toast.makeText(getActivity(), output, Toast.LENGTH_SHORT).show();
}
}
My adapter
package adapter;
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.LinearLayout;
import android.widget.TextView;
import com.transvision.bertho.transvisiondashboardapp.R;
import java.util.List;
import model.Channel;
public class ChannelAdapter extends RecyclerView.Adapter<ChannelAdapter.ChannelViewHolder> {
private List<Channel> channels;
private int rowLayout;
private Context context;
public static class ChannelViewHolder extends RecyclerView.ViewHolder {
LinearLayout moviesLayout;
TextView movieTitle;
TextView data;
TextView movieDescription;
TextView rating;
TextView name;
TextView code;
TextView description;
TextView number;
TextView definition;
TextView paket;
ImageView logo;
public ChannelViewHolder(View v) {
super(v);
moviesLayout = (LinearLayout) v.findViewById(R.id.movies_layout);
name = (TextView) v.findViewById(R.id.title);
definition = (TextView) v.findViewById(R.id.subtitle);
description = (TextView) v.findViewById(R.id.description);
// rating = (TextView) v.findViewById(R.id.rating);
}
}
public ChannelAdapter(List<Channel> channels, int rowLayout, Context context) {
this.channels = channels;
this.rowLayout = rowLayout;
this.context = context;
}
#Override
public ChannelAdapter.ChannelViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(rowLayout, parent, false);
return new ChannelViewHolder(view);
}
#Override
public void onBindViewHolder(ChannelViewHolder holder, final int position) {
holder.name.setText(channels.get(position).getName());
holder.definition.setText(channels.get(position).getDefinition());
holder.description.setText(channels.get(position).getDescription());
// holder.rating.setText(channels.get(position).getVoteAverage().toString());
}
#Override
public int getItemCount() {
return channels.size();
}
}
Is there anything wrong in my code? Or wrong in code placement?
Thanks
Getting data from internet is an async task and may takes too long, here you don't bind any adapter to the recyclerView until you get a response and this is not the usual right way, If you don't get any response for some reasons (e.g no internet connection), then recyclerView.setAdapter won't run, So I suggest you to create an empty adapter first, Then whenever you get response just update the adapter :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.movies_recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
//Pass empty list to (predefined) adapter
adapter = new ChannelAdapter (new ArrayList<>(), rowLayout, getActivity());
//Bind it to recyclerView
recyclerView.setAdapter(adapter);
getChannelData();
// Inflate the layout for this fragment
return rootView;
}
Add some method to your adapter in case you want add Channel :
public void addChannel(Channel channel) {
channels.add(channel);
notifyDatasetChanged();//even better notifyItemInserted();
}
Now in your response listener add the response body that you got to the adapter:
#Override
public void onResponse(Call<ChannelResponse> call, Response<ChannelResponse> response) {
//Use a loop to add channels you got
adapter.addChannel(responsebodyItems);
}

RecyclerView Data is not showing up

I am trying to create Navigation Drawer with RecyclerView. I am following a tutorial on YouTube to do this because I am new to this. The problem is RecyclerView does not show any data from the adapter. I need help. Any suggestion on this is appreciated.
NavigationDrawerFragment.java
package com.pixalstudio.cakedekho;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {#link Fragment} subclass.
*/
public class NavigationDrawerFragment extends Fragment {
int i=0;
private RecyclerView recyclerView;
public static final String PREF_FILE_NAME = "testpref";
public static final String KEY_USER_LEARNED_DRAWER = "user_learned_drawer";
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private InfoAdapter adapter;
private boolean mUserLearnedDrawer;
private boolean mFromSavedInstanceState;
private View containerView;
public NavigationDrawerFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mUserLearnedDrawer = Boolean.valueOf(readFromPreferences(getActivity(), KEY_USER_LEARNED_DRAWER, "false"));
if (savedInstanceState != null) {
mFromSavedInstanceState = true;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View layout = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
recyclerView = (RecyclerView) layout.findViewById(R.id.drawerList);
adapter = new InfoAdapter(getActivity(), getData());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return layout;
}
public List<Information> getData() {
List<Information> data = new ArrayList<>();
int[] icons = {R.drawable.seven1, R.drawable.seven2, R.drawable.seven3, R.drawable.seven4};
String[] titles = {"Login", "Location", "Home", "About Us"};
for (int i=0; i < titles.length && i < icons.length; i++) ;
{
Information current = new Information();
current.iconId = icons[i];
current.title = titles[i];
data.add(current);
}
return data;
}
public void setUp(int fragmentId, DrawerLayout drawerLayout, final Toolbar toolbar) {
containerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mDrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!mUserLearnedDrawer) {
mUserLearnedDrawer = true;
saveToPreferences(getActivity(), KEY_USER_LEARNED_DRAWER, mUserLearnedDrawer + "");
}
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
getActivity().invalidateOptionsMenu();
}
};
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(containerView);
}
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
}
public static void saveToPreferences(Context context, String preferenceName, String preferenceValue) {
SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(preferenceName, preferenceValue);
editor.apply();
}
public static String readFromPreferences(Context context, String preferenceName, String defaultValue) {
SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(preferenceName, defaultValue);
}
}
Information.java
package com.pixalstudio.cakedekho;
/**
* Created by akkie on 7/10/2015.
*/
public class Information {
int iconId;
String title;
}
InfoAdapter.java
package com.pixalstudio.cakedekho;
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 java.util.Collections;
import java.util.List;
/**
* Created by akkie on 7/10/2015.
*/
public class InfoAdapter extends RecyclerView.Adapter<InfoAdapter.MyViewHolder> {
List<Information> data = Collections.emptyList();
private LayoutInflater inflater;
public InfoAdapter(Context context, List<Information> data) {
inflater = LayoutInflater.from(context);
this.data = data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.customrow, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Information current = data.get(position);
holder.title.setText(current.title);
holder.icon.setImageResource(current.iconId);
}
#Override
public int getItemCount() {
return data.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView title;
ImageView icon;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.listText);
icon = (ImageView) itemView.findViewById(R.id.listIcon);
}
}
}
customrow.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
>
<ImageView
android:id="#+id/listIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:padding="8dp"
android:src="#drawable/seven1" />
<TextView
android:id="#+id/listText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:padding="8dp"
android:text="Dummy Text" />
</LinearLayout>
fragment_navigation_drawer.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#DADADA"
tools:context="com.pixalstudio.cakedekho.NavigationDrawerFragment">
<LinearLayout
android:id="#+id/containerDrawerImage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FB8C00">
<ImageView
android:layout_width="240dp"
android:layout_height="140dp"
android:src="#drawable/ic_abstract1" />
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:layout_below="#+id/containerDrawerImage"
android:id="#+id/drawerList"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
Please let me know if anyone needs any other information to fix my problem. Thank you in advance.

Categories