I'm a beigner working on firebase java android. My problem is that i cannot load the recyclerView it is showing that adapter not attached Skipping layout even though I've attached the adapter still its showing the same
Below is my code please help me. Thanks in advance
private RecyclerView bookList,listOrg,listcustom;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_work_employee);
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
MyCustomWorkRef = FirebaseDatabase.getInstance().getReference().child("WorksCustomAdded");
bookList = findViewById(R.id.myCustomerList);
listcustom = findViewById(R.id.myCustomerListCustom);
bookList.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MyWorkEmployeeActivity.this);
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
bookList.setLayoutManager(linearLayoutManager);
listcustom.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager2 = new LinearLayoutManager(MyWorkEmployeeActivity.this);
linearLayoutManager2.setReverseLayout(true);
linearLayoutManager2.setStackFromEnd(true);
listcustom.setLayoutManager(linearLayoutManager2);
//LoadDat();
DisplayCustom("ltG284DWVbbxfHlD3vAiiwkEv963","22883b15-d432-42b7-8ba5-1b3d4586ff09");
// DisplayCustom();
}
This is my Display Custom Function
private void DisplayCustom(String cmpnyUID,String empId) {
Toast.makeText(getApplicationContext(), "CompnUID : " + cmpnyUID + "\n empID : "+empId, Toast.LENGTH_SHORT).show();
Query SortPostsInDecendingOrder = MyCustomWorkRef.child(cmpnyUID).orderByChild("empID").equalTo(empId);;
FirebaseRecyclerOptions<MyCustomer> options = new FirebaseRecyclerOptions.Builder<MyCustomer>()
.setQuery(SortPostsInDecendingOrder, MyCustomer.class)
.build();
FirebaseRecyclerAdapter<MyCustomer, MyWorkEmployeeActivity.PBooksViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<MyCustomer, MyWorkEmployeeActivity.PBooksViewHolder>(options)
{
#NonNull
#Override
public MyWorkEmployeeActivity.PBooksViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i)
{
View view= LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.viewwork_list_eng, viewGroup, false);
MyWorkEmployeeActivity.PBooksViewHolder viewHolder =new MyWorkEmployeeActivity.PBooksViewHolder(view);
return viewHolder;
}
#Override
protected void onBindViewHolder(#NonNull MyWorkEmployeeActivity.PBooksViewHolder holder, int position, #NonNull MyCustomer model)
{
final String pos = getRef(position).getKey();
String cmpnyID = model.getCmpnyID();
String wrkID = model.getWrkSiteID();
String engID = model.getEngKey();
String usrID = model.getUsrkey();
holder.bookname.setText(model.getUsrname());
holder.count.setText("Work No: \n"+model.getCnt());
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent reqIntent = new Intent(MyWorkEmployeeActivity.this, ViewCustomWrkActivity.class);
reqIntent.putExtra("wrkID", model.getWrkSiteID());
reqIntent.putExtra("usrkey","0");
startActivity(reqIntent);
}
});
}
};
listcustom.setAdapter(firebaseRecyclerAdapter);
firebaseRecyclerAdapter.startListening();
}
public class PBooksViewHolder extends RecyclerView.ViewHolder {
TextView bookname, bookauthor,fees ,count;
ImageView profImage;
LinearLayout mView;
String t_area, b_area, plan, allow;
public PBooksViewHolder(#NonNull View itemView) {
super(itemView);
profImage = itemView.findViewById(R.id.ivRequestProfile);
bookname = itemView.findViewById(R.id.tvRequestUserName);
bookauthor = itemView.findViewById(R.id.tvWorksCompletedEngineerList);
mView = itemView.findViewById(R.id.request_layout);
fees = itemView.findViewById(R.id.tvFeesEngineerList);
count = itemView.findViewById(R.id.wrkCount);
}
}
I found the answer for this problem. In My xml File I've been using match_parent on the height. Which caused the main thread to skip the layout, because it couldn't find the layout scales.
So I changed the value to some standard height in dp. Eg: 600dp. Which defined the layout correctly so now the recyclerView is loading perfectly without skipping the layout.
my XML Code
`
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/myWorkListemp"
android:layout_width="match_parent"
android:layout_height="700dp"
android:layout_marginTop="15dp" />
<androidx.recyclerview.widget.RecyclerView
android:visibility="gone"
android:id="#+id/myCustomerListCustom"
android:layout_width="match_parent"
android:layout_height="700dp"
android:layout_marginTop="15dp" />
</LinearLayout>
`
Related
The button view shows confirming that the fragment shows, however the recycler view doesn't.
The logged array size of "jobs" is 1, confirming that getItemCount() isn't the problem and that the recycler adapter constructor is called. I'm reusing my JobRecyclerAdapter class but nothing's static, so there shouldn't be any interference between the two instances. The layout is a a copy of a working one I have, minus different ids and layout name, so that shouldn't be a problem either. There are no errors.
Layout
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
>
<include layout="#layout/top_bar"
android:id="#+id/topBarAJ"
android:layout_height="wrap_content"
android:layout_width="match_parent"
app:layout_constraintTop_toTopOf="parent"/>
<include layout="#layout/bottom_bar"
android:id="#+id/bottomBarAJ"
android:layout_height="wrap_content"
android:layout_width="match_parent"
app:layout_constraintBottom_toBottomOf="parent"/>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/activeJobRecyclerView"
app:layout_constraintTop_toBottomOf="#id/topBarAJ"
app:layout_constraintBottom_toTopOf="#id/bottomBarAJ"/>
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
app:layout_constraintBottom_toTopOf="#+id/activeJobRecyclerView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.505"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/topBarAJ" />
</androidx.constraintlayout.widget.ConstraintLayout>
RecyclerAdapter
List<Job> jobs;
List<Drawable> images;
RecyclerViewClickListener clickListener;
public JobRecyclerAdapter(List<Job> downloadedJobs, List<Drawable> images, RecyclerViewClickListener clickListener) {
this.jobs = downloadedJobs;
this.images = images;
Integer arraySize = images.size();
Log.d("downloadActiveJob", "JobRecyclerAdapter: images array size: " + arraySize.toString());
arraySize = jobs.size();
Log.d("downloadActiveJob", "JobRecyclerAdapter: jobs array size: " + arraySize.toString());
this.clickListener = clickListener;
}
class JobCardViewHolder extends RecyclerView.ViewHolder {
public ImageView itemImage;
public TextView itemName;
public TextView itemWeight;
public TextView itemSize;
public TextView transmitterName;
public JobCardViewHolder(View v) {
super(v);//call default constructor
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("RecyclerView", "onClick:" + getAdapterPosition());
clickListener.recyclerViewListClicked(v, getAdapterPosition());
}
});
itemImage = (ImageView) v.findViewById(R.id.itemImage);
itemName = (TextView) v.findViewById(R.id.itemName);
itemWeight = v.findViewById(R.id.itemWeight);
itemSize = v.findViewById(R.id.itemSize);
transmitterName = v.findViewById(R.id.transmitterName);
}
}
public void removeItem(int jobIndex) {
jobs.remove(jobIndex);
notifyDataSetChanged();
}
#Override
public JobCardViewHolder onCreateViewHolder(ViewGroup vg, int n) {
View v = LayoutInflater.from(vg.getContext()).inflate(R.layout.job_card_layout, vg, false);
JobCardViewHolder vH = new JobCardViewHolder(v);
return vH;
}
#Override
public void onBindViewHolder(JobCardViewHolder vH, int position) {
vH.itemName.setText(jobs.get(position).itemName);
vH.itemImage.setImageDrawable(images.get(position));
vH.itemWeight.setText(jobs.get(position).itemWeight);
vH.itemSize.setText(jobs.get(position).itemSize);
vH.transmitterName.setText(jobs.get(position).transmitterName);
}
#Override
public int getItemCount() {
return jobs.size();
}
}
Fragment (I only showed the relevant parts of the fragment.)
RecyclerView jobRecyclerView;
JobRecyclerAdapter jobRecyclerAdapter;
LinearLayoutManager llm;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.sub_fragment_active_jobs_1, container, false);
this.jobRecyclerView = view.findViewById(R.id.activeJobRecyclerView);
return view;
}
public void configureJobsRecyclerAdapter(Job activeJob, List<Drawable> imageDrawables) {
Log.d("downloadActiveJob", "configureJobRecyclerAdapter called");
List<Job> downloadedJobs = new ArrayList<>();
downloadedJobs.add(activeJob);
Integer arraySize = imageDrawables.size();
Log.d("downloadActiveJob", "configureJobRecyclerAdapter: " + arraySize.toString());
jobRecyclerAdapter = new JobRecyclerAdapter(downloadedJobs, imageDrawables, this);
llm = new LinearLayoutManager(context);
jobRecyclerView.setLayoutManager(llm);
jobRecyclerView.setAdapter(jobRecyclerAdapter);
}
Update: If I move the recycler view/adapter setup code to onResume, the recycler view is visible. When I update the recycler view with a new adapter, the recycler view becomes invisible.
If I can't solve it using this new discovery I'll post the whole fragment.
Hey, you create the function configureJobsRecyclerAdapter() but didn't call it inside fragment onCreateView(). Like...
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.sub_fragment_active_jobs_1, container, false);
this.jobRecyclerView = view.findViewById(R.id.activeJobRecyclerView);
configureJobsRecyclerAdapter()//Add this line.
return view;
}
if you are fetching data which are required for configureJobsRecyclerAdapter() from an api maybe you are setting empty list at the time when you are calling configureJobsRecyclerAdapter(). and that's why when you call it in onResume, the list becomes visible(because then data is fetched).
and don't forget to call adapter.notifyDataSetChanged() after each change in your list.
I have a RecyclerView implementing a LinearLayout of CardViews through an adapter. Inside each CardView, I have a spinner. What I need to do is get the CardViews position when a spinner is selected. Ex.. if I have 10 CardViews in a list on the screen with a spinner in each, and a select a value from the spinner in the 5th item, I need to get that 5th position as well as the selected value.
I'm able to get the selected value just fine. The issue is with getting the CardViews position. The CardViews are being generated from an ArrayList.
I will include my code below along with an image of the desired results. Any help is greatly appreciated!!
RecyclerView Adapter
public class PopularAdapter extends RecyclerView.Adapter<PopularAdapter.MyViewHolder> {
PopularFragment mPopularFragment;
private Context mContext;
private ArrayList<GameData> gameDataArr = new ArrayList<GameData>();
private String userId;
public PopularAdapter(Context context, ArrayList<GameData> gameDataArr, PopularFragment mPopularFragment, String userId) {
mContext = context;
this.gameDataArr = gameDataArr;
this.mPopularFragment = mPopularFragment;
this.userId = userId;
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView title;
public ImageView thumbnail;
private CardView mCardView;
PopularFragment mPopularFragment;
Spinner mGameSpinner;
LinearLayout mSpinnerLayout;
public MyViewHolder(View view, final PopularFragment mPopularFragment, final String userId) {
super(view);
this.mPopularFragment = mPopularFragment;
mSpinnerLayout = (LinearLayout) view.findViewById(R.id.spinner_layout);
title = (TextView) view.findViewById(R.id.item_title);
thumbnail = (ImageView) view.findViewById(R.id.item_main_img);
mCardView = (CardView) view.findViewById(R.id.item_cardview);
mCardView.setOnClickListener(this);
mGameSpinner = (Spinner) view.findViewById(R.id.game_spinner_options);
mGameSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long l) {
//String ASIN = gameDataArr.get(position).getAmazonId();
System.out.println(parent.getId()); // <--- prints the same value for each item.
if(userId == null){
Toast.makeText(mPopularFragment.getActivity(), "You must be logged in.", Toast.LENGTH_LONG).show();
return;
}
FirebaseDbHelper mFirebaseDbHelper = new FirebaseDbHelper();
if(position == 0){
// remove from db
// mFirebaseDbHelper.removeOwnedGame(ASIN, userId);
} else if(position == 1){
// add to owned games
// mFirebaseDbHelper.addOwnedGame(ASIN, userId);
} else {
// add to wishlist games
// mFirebaseDbHelper.addWishlistGame(ASIN, userId);
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
#Override
public void onClick(View view) {
System.out.println("click: " + getPosition());
//mPopularFragment.openGameActivity(getPosition());
}
}
#Override
public PopularAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
System.out.println("parent: " + parent);
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item, parent, false);
return new PopularAdapter.MyViewHolder(itemView, mPopularFragment, userId);
}
#Override
public void onBindViewHolder(final PopularAdapter.MyViewHolder holder, final int position) {
GameData game = gameDataArr.get(position);
holder.title.setText(game.getTitle());
Picasso.with(mContext).load(game.getFeatImgUrl()).resize(160, 200).into(holder.thumbnail);
}
#Override
public int getItemCount() {
return gameDataArr.size();
}
}
CardView
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/item_cardview"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_marginBottom="0dp"
card_view:cardCornerRadius="4dp"
>
<LinearLayout
android:padding="16dp"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/item_main_img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_toLeftOf="#+id/right_content"
android:scaleType="fitXY"
android:adjustViewBounds="false"/>
<LinearLayout
android:id="#+id/right_content"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/item_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="16dp" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Spinner
android:id="#+id/game_spinner_options"
android:entries="#array/game_dropdown"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></Spinner>
<Button
android:text="Buy Now"
android:id="#+id/game_buy_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
Popular Fragment
public class PopularFragment extends Fragment {
#BindView(R.id.popular_recyclerView)
RecyclerView mPopularRecyclerView;
private RecyclerView.Adapter mAdapter;
private ArrayList<GameData> gamesArray = new ArrayList<GameData>();
ApiResultsObject apiResults;
private FirebaseAuth auth;
private FirebaseUser user;
private FirebaseAuth.AuthStateListener authListener;
private String userId;
public PopularFragment() {
// Required empty public constructor
}
#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_popular, container, false);
ButterKnife.bind(this, view);
// bus instance
MyBus.getInstance().register(this);
// get api url
// trigger async task
// use results
String amazonApiUrl = getAmazonApiUrl();
if(amazonApiUrl != null){
new AmazonAsyncTask().execute(amazonApiUrl);
}
//get firebase auth instance
auth = FirebaseAuth.getInstance();
//get current user
user = FirebaseAuth.getInstance().getCurrentUser();
//add a auth listener
authListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
System.out.println("User logged in. Game activity.");
userId = user.getUid();
} else {
// User is signed out
System.out.println("User not logged in. Game activity");
}
}
};
// Inflate the layout for this fragment
return view;
}
private String getAmazonApiUrl() {
String amazonApiUrl = "";
AmazonQuery amazonQuery = new AmazonQuery("ItemSearch");
amazonApiUrl = amazonQuery.buildUrl();
return amazonApiUrl;
}
private void setData(ApiResultsObject data) {
gamesArray = data.getGamesArray();
if (data != null) {
mAdapter = new PopularAdapter(getActivity().getBaseContext(), gamesArray, this, userId);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
mPopularRecyclerView.setLayoutManager(mLayoutManager);
mPopularRecyclerView.setAdapter(mAdapter);
}
}
#Subscribe
public void onAsyncTaskResults(BrowseAsyncTaskResult event) {
apiResults = event.getResults();
if (apiResults != null) {
setData(apiResults);
}
}
#Override
public void onDestroy() {
MyBus.getInstance().unregister(this);
super.onDestroy();
}
#Override
public void onStart() {
super.onStart();
auth.addAuthStateListener(authListener);
}
#Override
public void onStop() {
super.onStop();
if (authListener != null) {
auth.removeAuthStateListener(authListener);
}
}
}
You can set an OnClickListener on mGameSpinner in your onBindViewHolder().
onBindViewHolder(final PopularAdapter.MyViewHolder holder, final int position)
You can then store/use the position parameter as it will be the index into your gameArray for that particular spinner. You can then use that index to grab the spinner's currently selected value and do whatever you need to do with it.
I think you should set a tag for each view in the RV through the holder in onBindViewHolder. Something like:
holder.itemView.setTag(game.getId());
The game's Id should be one of the data points in the ArrayList you passed into the Adpater. So it'd be easier to add a getId() method to your game object.
Once you have an integer Id to call on that's unique to each game in the list, you can simply find that Id within the Spinner's onItemSelectedListener with:
int ID = (int) holder.itemView.getTag();
Then you can use ID within your if-else statements to know which game within your card list the spinner is selected for.
#Override
public void onBindViewHolder(final LanguagesAdapter.MyViewHolder holder, final int position) {
holder.edit_language_name.setText(edit_languageDetails_ArrayList.get(position).getEt_language_name());
sp_langage_rating=edit_languageDetails_ArrayList.get(position).getEt_language_ratings();
String ss=sp_langage_rating;
if(sp_langage_rating != null) {
if(sp_langage_rating.equals("Beginner"))
{
adapterLanguage = new ArrayAdapter<CharSequence>(context, R.layout.my_spinner_items, strarray_language);
adapterLanguage.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.sp_languages.setAdapter(adapterLanguage);
}
else if(sp_langage_rating.equals("Intermediate")) {
adapterLanguage = new ArrayAdapter<CharSequence>(context, R.layout.my_spinner_items, strarray_language1);
adapterLanguage.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.sp_languages.setAdapter(adapterLanguage);
}else if(sp_langage_rating.equals("Expert")){
adapterLanguage = new ArrayAdapter<CharSequence>(context, R.layout.my_spinner_items, strarray_language2);
adapterLanguage.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.sp_languages.setAdapter(adapterLanguage);
}
}else{
adapterLanguage = new ArrayAdapter<CharSequence>(context, R.layout.my_spinner_items, strarray_language);
adapterLanguage.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.sp_languages.setAdapter(adapterLanguage);
}
Log.d("print","yes");
}
So here is the gist of the issue, I have implemented RecyclerViews in several activities successfully, however this particular RecyclerView DOES NOT DISPLAY ANYTHING!
I have created a fragment within a tablayout to display, and also rewritten the code thrice. Here is the code for the entire fragment(View is inflating fine, along with a searchbar on top of the recycler) adapter is at the bottom. I have left OnBindViewHolder blank on purpose as I wrote it twice before aldready without any results. Any help would be appreciated.
Fragment + Adapter code:
public static class EditJob extends Fragment {
ServerRequests serverRequests;
UserLocalStore userLocalStore;
User receivedUser;
EditText searchJob;
ImageView searchBtn;
RecyclerView editJobRecycler;
MyRecyclerAdapter editJobAdapter;
ArrayList<Job> arrayJob;
TextView noJobSearch;
#Override
public void onAttach(Context context) {
super.onAttach(context);
serverRequests = new ServerRequests(context);
userLocalStore = new UserLocalStore(context);
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_edit_job, container, false);
receivedUser = userLocalStore.getAllDetails();
arrayJob = new ArrayList<>();
noJobSearch = (TextView) view.findViewById(R.id.noJobEdit);
searchJob = (EditText) view.findViewById(R.id.etEditJob);
searchBtn = (ImageView) view.findViewById(R.id.editJobImage);
editJobRecycler = (RecyclerView) view.findViewById(R.id.jobEditRecycler);
editJobAdapter = new MyRecyclerAdapter(arrayJob);
editJobRecycler.setLayoutManager(new LinearLayoutManager(getContext()));
editJobRecycler.setAdapter(editJobAdapter);
searchBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
searchJob();
}
});
return view;
}
public void searchJob() {
arrayJob.clear();
serverRequests.searchJobListings(searchJob.getText().toString(), new GetJobObjectsCallBack() {
#Override
public void done(Job[] returnedJobs) {
if (returnedJobs == null || returnedJobs.length == 0) {
noJobSearch.setVisibility(View.VISIBLE);
} else {
noJobSearch.setVisibility(View.GONE);
for (int i = 0; i < returnedJobs.length; i++) {
arrayJob.add(i, returnedJobs[i]);
}
editJobAdapter = new MyRecyclerAdapter(arrayJob);
editJobRecycler.setAdapter(editJobAdapter);
editJobAdapter.notifyDataSetChanged();
}
}
});
}
private class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecyclerAdapter.VH> {
ArrayList<Job> jobArray;
public MyRecyclerAdapter(ArrayList<Job> jl) {
jobArray = jl;
}
public class VH extends RecyclerView.ViewHolder {
TextView jobID, jobPosition, jobExperience, jobRemarks, jobLocation, jobDescription, jobDomain;
EditText etjobID, etjobPosition, etjobExperience, etjobRemarks, etjobLocation, etjobDescription, etjobDomain;
Button bEditJob;
public VH(View v) {
super(v);
jobID = (TextView) v.findViewById(R.id.returnedJobID);
jobExperience = (TextView) v.findViewById(R.id.returnedJobExperience);
jobRemarks = (TextView) v.findViewById(R.id.returnedJobRemarks);
jobLocation = (TextView) v.findViewById(R.id.returnedJobLocation);
jobDescription = (TextView) v.findViewById(R.id.returnedJobDescription);
jobDomain = (TextView) v.findViewById(R.id.returnedJobDomain);
jobPosition = (TextView) v.findViewById(R.id.returnedJobPosition);
etjobID = (EditText) v.findViewById(R.id.etreturnedJobID);
etjobPosition = (EditText) v.findViewById(R.id.etreturnedJobPosition);
etjobExperience = (EditText) v.findViewById(R.id.etreturnedJobExperience);
etjobRemarks = (EditText) v.findViewById(R.id.etreturnedJobRemarks);
etjobLocation = (EditText) v.findViewById(R.id.etreturnedJobLocation);
etjobDescription = (EditText) v.findViewById(R.id.etreturnedJobDescription);
etjobDomain = (EditText) v.findViewById(R.id.etreturnedJobDomain);
bEditJob = (Button) v.findViewById(R.id.bEditJob);
}
}
#Override
public VH onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater li = LayoutInflater.from(parent.getContext());
View v = li.inflate(R.layout.job_edit_listview, parent);
return new VH(v);
}
#Override
public void onBindViewHolder(VH holder, int position) {
Job current = jobArray.get(position);
}
#Override
public int getItemCount() {
System.out.println("jobarray size = " + jobArray.size());
return jobArray.size();
}
}
}
XML for the fragment:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
style="#style/FloatingTextView"
android:layout_marginTop="10dp"
android:elevation="6dp"
android:layout_width="match_parent"
android:layout_height="50dp"
android:animateLayoutChanges="true">
<EditText
android:id="#+id/etEditJob"
style="#style/FloatingTextView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_margin="0.5dp"
android:layout_centerVertical="true"
android:layout_toLeftOf="#+id/editJobDivider"
android:elevation="0dp"
android:hint="Enter a search term"
android:translationZ="0dp" />
<View
android:id="#+id/editJobDivider"
android:layout_width="1dp"
android:layout_height="40dp"
android:layout_centerVertical="true"
android:layout_toLeftOf="#+id/editJobImage"
android:alpha="0.2"
android:background="#color/Black" />
<ImageView
android:id="#+id/editJobImage"
style="#style/FloatingTextView"
android:layout_width="47dp"
android:layout_height="fill_parent"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_margin="1dp"
android:alpha="0.5"
android:clickable="true"
android:elevation="0dp"
android:padding="10dp"
android:src="#drawable/ic_search_black_48dp"
android:translationZ="0dp" />
</RelativeLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="No Jobs match your query"
android:id="#+id/noJobEdit"/>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="2dp"
android:id="#+id/jobEditRecycler"/>
</LinearLayout>
PS: I have checked the dataset which is returning a size on querying the database, the adapter has been notified too and the getItemCount returns a non-zero size. I am honestly clueless as to what the problem is!
EDIT: Here is the (almost) identical code i used for another static inner class fragment. This implementation works just fine.
public static class JobSearcher extends Fragment {
EditText searchJob;
ImageView searchImage;
RecyclerView searchJobListView;
ArrayList<Job> arrayJob;
ServerRequests serverRequests;
Context parentActivity;
UserLocalStore userLocalStore;
TextView noJobSearch;
MyJobRecyclerAdapter jobArrayAdapter;
User receivedUser;
#Override
public void onAttach(Context activity) {
super.onAttach(activity);
parentActivity = activity;
serverRequests = new ServerRequests(activity);
userLocalStore = new UserLocalStore(activity);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_search_job, container, false);
searchJob = (EditText) v.findViewById(R.id.searchJobEditText);
searchImage = (ImageView) v.findViewById(R.id.searchJobImage);
receivedUser = userLocalStore.getAllDetails();
noJobSearch = (TextView) v.findViewById(R.id.noJobSearch);
searchImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
searchJob();
}
});
searchJobListView = (RecyclerView) v.findViewById(R.id.jobSearchRecycler);
arrayJob = new ArrayList<>();
jobArrayAdapter = new MyJobRecyclerAdapter(arrayJob);
searchJobListView.setLayoutManager(new LinearLayoutManager(getContext()));
searchJobListView.setAdapter(jobArrayAdapter);
return v;
}
public void searchJob() {
arrayJob.clear();
serverRequests.searchJobListings(searchJob.getText().toString(), new GetJobObjectsCallBack() {
#Override
public void done(Job[] returnedJobs) {
if (returnedJobs == null || returnedJobs.length == 0) {
noJobSearch.setVisibility(View.VISIBLE);
} else {
noJobSearch.setVisibility(View.GONE);
for (int i = 0; i < returnedJobs.length; i++) {
arrayJob.add(i, returnedJobs[i]);
}
jobArrayAdapter = new MyJobRecyclerAdapter(arrayJob);
searchJobListView.setAdapter(jobArrayAdapter);
jobArrayAdapter.notifyDataSetChanged();
}
}
});
}
public class MyJobRecyclerAdapter extends RecyclerView.Adapter<MyJobRecyclerAdapter.ViewHolder> {
ArrayList<Job> arrayJob = new ArrayList<>();
public MyJobRecyclerAdapter(ArrayList<Job> jl) {
arrayJob = jl;
}
#Override
public MyJobRecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater li = LayoutInflater.from(parent.getContext());
View inflatedView = li.inflate(R.layout.job_item_list, parent, false);
ViewHolder VH = new ViewHolder(inflatedView);
return VH;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Job currentJob = arrayJob.get(position);
holder.jobDesc.setText("Job Description: " + currentJob.getDescription());
holder.jobID.setText("ID: " + currentJob.getID());
holder.jobRemarks.setText("Remarks: " + currentJob.getRemarks());
holder.jobExperience.setText("Experience Required: " + currentJob.getExperience() + " years");
holder.jobDomain.setText("Domain: " + currentJob.getDomain());
holder.jobLoc.setText("Location: " + currentJob.getLocation());
holder.jobType.setText("Type: " + currentJob.getType());
holder.jobPos.setText("Position: " + currentJob.getPosition());
}
#Override
public int getItemCount() {
return arrayJob.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView jobID, jobDesc, jobType, jobLoc, jobPos, jobRemarks, jobExperience, jobDomain;
Button applyForJob;
public ViewHolder(View itemView) {
super(itemView);
jobID = (TextView) itemView.findViewById(R.id.returnedJobID);
jobDesc = (TextView) itemView.findViewById(R.id.returnedJobDescription);
jobLoc = (TextView) itemView.findViewById(R.id.returnedJobLocation);
jobType = (TextView) itemView.findViewById(R.id.returnedJobType);
jobPos = (TextView) itemView.findViewById(R.id.returnedJobPosition);
jobRemarks = (TextView) itemView.findViewById(R.id.returnedJobRemarks);
jobExperience = (TextView) itemView.findViewById(R.id.returnedJobExperience);
jobDomain = (TextView) itemView.findViewById(R.id.returnedJobDomain);
applyForJob = (Button) itemView.findViewById(R.id.bApplyJob);
applyForJob.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bApplyJob:
serverRequests.applyForJob(receivedUser.getEmail(), receivedUser.getName(), jobID.getText().toString(), jobPos.getText().toString());
}
}
}
}
Your ViewHolder must work with views for display. Example:
public VH(View v) {
super(v);
jobLocation = (TextView) v.findViewById(R.id.returnedJobLocation);
jobLocation.setText("something location");
}
I have been trying to figure this problem out for quite a while now, but i just can't figure out what the problem is. The aim is to make a request to Songkick api (which is json), which will return the upcoming events of artist and populate it on the the fragment. The request works fine, but it doesn't come on the screen using recyclerView.
This is my xml:
<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"
tools:context="com.example.artispot.fragments.FragmentEvents">
<android.support.v7.widget.RecyclerView
android:id="#+id/List"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
This is the Adapter:
public class AdapterEvents extends RecyclerView.Adapter<AdapterEvents.ViewHolderEvents> {
private LayoutInflater layoutInflater;
private String cls = "TAG";
private ArrayList<Events> listEvents = new ArrayList<>();
public AdapterEvents(Context context){
layoutInflater = LayoutInflater.from(context);
}
public void setListEvents(ArrayList<Events> listEvents){
this.listEvents = listEvents;
notifyItemRangeChanged(0,listEvents.size());
}
#Override
public ViewHolderEvents onCreateViewHolder(ViewGroup parent, int viewType) {
View view = layoutInflater.inflate(R.layout.custom_events,parent,false);
ViewHolderEvents viewHolder =new ViewHolderEvents(view);
return viewHolder;
}
//create an object for each textview
#Override
public void onBindViewHolder(ViewHolderEvents holder, int position) {
Events currentEvent = listEvents.get(position);
holder.DateTextView.setText(currentEvent.getStartDate());
// + "--"+ currentEvent.getEndDate()
holder.displayName.setText(currentEvent.getDisplayName());
holder.Venue.setText(currentEvent.getVenue());
}
#Override
public int getItemCount() {
return listEvents.size();
}
static class ViewHolderEvents extends RecyclerView.ViewHolder{
private TextView DateTextView;
private TextView displayName;
private TextView Venue;
public ViewHolderEvents(View itemView){
super(itemView);
DateTextView = (TextView) itemView.findViewById(R.id.DateTextView);
displayName = (TextView) itemView.findViewById(R.id.displayName);
Venue = (TextView) itemView.findViewById(R.id.Venue);
}
}
}
and this part is from my fragment class:
public void sendRequest(){
// Formulate the request and handle the response.
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,
getRequestUrl(),(String)null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse( JSONObject response) {
listEvents= parseJSONResponse(response);
adapterEvents.setListEvents(listEvents);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Handle error
}
});
requestQueue.add(request);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_events, container,false);
recyclerView = (RecyclerView)view.findViewById(R.id.List);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
adapterEvents = new AdapterEvents(getActivity());
recyclerView.setAdapter(adapterEvents);
return view;
}
I have been on this for about a few days, and it's sort of frustrating because it's my project that is due in a week time. Any sort of help will be much appreciated. Thanks in advance.
I have been having difficulties making my device register button clicks within an android recyclerview and am not sure why it is not responding as I have looked around and it seems as though it should work. But what I really want to know is if I have put stuff in the wrong place, am I missing something and if so what?
Holder Class
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView time;
public ImageButton button;
public ViewHolder(View v) {
super(v);
time = (TextView)v.findViewById(R.id.time);
button = (ImageButton)v.findViewById(R.id.imageButton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Test", "Button clicked");
}
});
}
}
Adapter Class
public class ListAdapter extends RecyclerView.Adapter<ViewHolder> {
// WIll hold the timer objects passed through
ArrayList<Timer> lData = null;
// Provide a suitable constructor (depends on the kind of dataset)
public ListAdapter(ArrayList<Timer> myDataset) {
lData = myDataset;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_adapter, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.time.setText(lData.get(position).getTime());
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return lData.size();
}
// Gets the timers
public ArrayList<Timer> getData() {
return lData;
}
}
Main Activity Class (OnCreate Method)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new ListAdapter(timers);
mRecyclerView.setAdapter(mAdapter);
}
View Item
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:padding="6dip"
android:layout_margin="6dip"
android:background="?android:selectableItemBackground">
<TextView
android:id="#+id/time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="fill_vertical"
android:textSize="28sp"
android:text="00:00:00"
android:paddingLeft="10dip"
android:layout_centerVertical="true"
android:layout_toEndOf="#+id/imageButton" />
<ImageButton
android:layout_width="50dip"
android:layout_height="wrap_content"
android:id="#+id/imageButton"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:src="#drawable/ic_action_pause"/>
</RelativeLayout>