No Adapter Attached; Skipping Layout when using retrofit - android

This is how I'm setting up my Recycler view in my Search Fragment. I don't understand why I keep getting the same error and what I'm missing.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_search, container, false);
searchText = (EditText)view.findViewById(R.id.searchText);
searchButton = (Button)view.findViewById(R.id.searchButton);
nutritionRecyclerView = (RecyclerView)view.findViewById(R.id.nutritionRecyclerView);
layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ApiClient.getInstance().getNutritionApiAdapter()
.getSearchResults(
AppDefines.APPLICATION_ID,
AppDefines.APPLICATION_KEY,
searchText.getText().toString())
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<SearchResultsModel>() {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
}
#Override
public void onNext(SearchResultsModel searchResultsModel) {
// On handling the http response, instantiate a new adapter with the results
adapter = new NutritionAdapter(searchResultsModel.getSearchResults());
adapter.setOnItemSelected(new NutritionAdapter.OnItemSelected() {
#Override
public void onSelected(NutritionItemModel item) {
if (onFragmentEvent != null) {
onFragmentEvent.onEvent(item);
}
}
});
// Assigning the LayoutManager to the RecyclerView
nutritionRecyclerView.setLayoutManager(layoutManager);
// Assigning the Adapter to the RecyclerView. If this isn't done, the view will not populate
nutritionRecyclerView.setAdapter(adapter);
}
});
}
});
return view;
}
Here is my ApiClient
public class ApiClient {
private static ApiClient instance;
public static ApiClient getInstance() {
if (instance == null) {
instance = new ApiClient();
}
return instance;
}
public NutritionApiAdapter getNutritionApiAdapter() {
NutritionApiAdapter api = new Retrofit.Builder()
.baseUrl(AppDefines.BASE_API_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build()
.create(NutritionApiAdapter.class);
return api;
}
}
And this is my NutritionApiAdapter
public interface NutritionApiAdapter {
#GET("item")
Observable<SearchResultsModel> getSearchResults(
#Query("_app_id") String appId,
#Query("_app_key") String appKey,
#Query("q") String searchString);
}
NutritionAdpater
public class NutritionAdapter extends RecyclerView.Adapter<NutritionItemViewHolder>{
private ArrayList<NutritionItemModel> nutritionItemCollection;
private OnItemSelected onItemSelected;
public NutritionAdapter(ArrayList<NutritionItemModel> nutritionItemCollection){
this.nutritionItemCollection = nutritionItemCollection;
}
#Override
public NutritionItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_nutrition, parent, false);
return new NutritionItemViewHolder(view);
}
#Override
public void onBindViewHolder(NutritionItemViewHolder holder,int position) {
NutritionItemModel item = nutritionItemCollection.get(position);
holder.setOnRecipeItemClicked(new NutritionItemViewHolder.OnNutritionItemClicked(){
#Override
public void onClick(NutritionItemModel item) {
if(onItemSelected != null) {
onItemSelected.onSelected(item);
}
}
});
// Bind the RecipeItemModel data to the view managed by the ViewHolder
holder.bind(item);
}
#Override
public final void onViewRecycled(final NutritionItemViewHolder holder) {
super.onViewRecycled(holder);
holder.setOnRecipeItemClicked(null);
holder.unbind();
}
#Override
public int getItemCount() {return nutritionItemCollection.size();}
public void setOnItemSelected(OnItemSelected onItemSelected) {
this.onItemSelected = onItemSelected;
}
public interface OnItemSelected {
void onSelected(NutritionItemModel item);
}
}
and NutritionItemViewHolder
public class NutritionItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView foodName;
private ImageView foodThumbnail;
private NutritionItemModel item;
private TextView item_name;
private TextView brand_name;
private OnNutritionItemClicked onNutritionItemClicked;
//todo add other elements here
public NutritionItemViewHolder(final View itemView) {super(itemView);}
public final void bind(final NutritionItemModel item) {
item_name = (TextView)itemView.findViewById(R.id.item_name);
brand_name = (TextView)itemView.findViewById(R.id.brand_name);
//foodThumbnail = (ImageView)itemView.findViewById(R.id.foodThumbnail);
//todo add other element id things here
/*
//used for preloading images
Glide.with(itemView.getContext())
.load(item.getSmallImageUrls().get(0))
.into(foodThumbnail);
*/
item_name.setText(item.getFields().getItem_name());
brand_name.setText(item.getFields().getBrand_name());
}
public final void unbind() {
//todo ?
//For later with butterknife
}
#Override
public void onClick(View v) {
if(onNutritionItemClicked != null) {
onNutritionItemClicked.onClick(item);
}
}
// The setter that allows other classes to create a reference to the listener.
public void setOnRecipeItemClicked(OnNutritionItemClicked onNutritionItemClicked) {
this.onNutritionItemClicked = onNutritionItemClicked;
}
// An interface is added as an internal implementation in our ViewHolder. This will allow
// classes that instantiate a new instance of this ViewHolder to subscribe to this interface
// and listen for events.
public interface OnNutritionItemClicked {
void onClick(NutritionItemModel item);
}
}

set the layoutmanager,
LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
list.setLayoutManager(llm);
list.setAdapter(adapter);
Maybe this can help you.

Related

Paging Library & Room : Content not loading when Recyclerview scroll

I'm trying to implement endless scrolling with recyclerview and Room using Paging Library in my application According to this article: https://developer.android.com/topic/libraries/architecture/paging/#database-examples
Some of the data is loaded at initialization but when user scroll, nothing happens, the rest of the data is not fetched
My Dao
#Dao
public interface MessageDao {
.
.
.
#Query("SELECT * FROM messages ORDER BY created DESC")
DataSource.Factory<Integer, Message> getPagedMessage();
}
ViewModel
public class SmsViewModel extends AndroidViewModel {
private LiveData<PagedList<Message>> liveData;
public SmsViewModel(#NonNull Application application) {
super(application);
DataSource.Factory<Integer, Message> factory = AppDatabase.getInstance(getApplication()).messageDao().getPagedMessage();
PagedList.Config config = (new PagedList.Config.Builder())
.setPageSize(10)
.setInitialLoadSizeHint(20)
.setPrefetchDistance(5)
.setEnablePlaceholders(false)
.build();
liveData = new LivePagedListBuilder<>(factory, config).build();
}
public LiveData<PagedList<Message>> getLiveData() {
return liveData;
}
}
Adapter class
public abstract class BasePagedAdapter<T> extends PagedListAdapter<T, BasePagedAdapter.MyViewHolder> {
private OnClickListener onClickListener;
private OnLongClickListener onLongClickListener;
public BasePagedAdapter(DiffUtil.ItemCallback<T> callback) {
super(callback);
}
public void setOnClickListener(OnClickListener onClickListener) {
this.onClickListener = onClickListener;
}
public void setOnLongClickListener(OnLongClickListener onLongClickListener) {
this.onLongClickListener = onLongClickListener;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
ViewDataBinding binding = DataBindingUtil.inflate(layoutInflater, getLayoutIdForType(viewType), parent, false);
return new MyViewHolder(binding);
}
#Override
public void onBindViewHolder(#NonNull BasePagedAdapter.MyViewHolder holder, int position) {
T t = getDataAtPosition(position);
holder.bind(t);
}
public abstract T getDataAtPosition(int position);
abstract #LayoutRes
public int getLayoutIdForType(int viewType);
class MyViewHolder extends RecyclerView.ViewHolder {
private final ViewDataBinding binding;
MyViewHolder(ViewDataBinding binding) {
super(binding.getRoot());
this.binding = binding;
itemView.setOnClickListener(v -> {
if (onClickListener != null) {
onClickListener.onClick(getAdapterPosition());
}
});
itemView.setOnLongClickListener(view -> {
if(onLongClickListener != null) {
onLongClickListener.onLongClick(getAdapterPosition());
return true;
}
return false;
});
}
void bind(T obj) {
binding.setVariable(BR.obj, obj);
binding.executePendingBindings();
}
}
public interface OnClickListener {
void onClick(int position);
}
public interface OnLongClickListener {
void onLongClick(int position);
}
}
Activity
public class SmsActivity extends AppCompatActivity {
#BindView(R.id.lyt_empty)
View lytEmpty;
#BindView(R.id.progressBar)
ProgressBar progressBar;
#BindView(R.id.recycler_view)
RecyclerView recyclerView;
PagedList<Message> messages;
BasePagedAdapter<Message> adapter = new BasePagedAdapter<Message>(DIFF_CALLBACK) {
#Override
public Message getDataAtPosition(int position) {
if (messages != null) {
return messages.get(position);
}
return null;
}
#Override
public int getLayoutIdForType(int viewType) {
return R.layout.item_sms_list;
}
};
SmsViewModel viewModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sms);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//noinspection ConstantConditions
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ButterKnife.bind(this);
viewModel = ViewModelProviders.of(this).get(SmsViewModel.class);
adapter.setOnClickListener(position -> {
Intent intent = new Intent(this, SmsDetailActivity.class);
intent.putExtra(SmsDetailActivity.EXTRA_SMS, messages.get(position));
startActivity(intent);
});
recyclerView.setAdapter(adapter);
recyclerView.setNestedScrollingEnabled(false);
loadData();
}
private void loadData() {
viewModel.getLiveData().observe(this, messages -> {
progressBar.setVisibility(View.GONE);
this.messages = messages;
if (messages != null && messages.size() > 0) {
adapter.submitList(messages);
recyclerView.setVisibility(View.VISIBLE);
lytEmpty.setVisibility(View.GONE);
} else {
recyclerView.setVisibility(View.GONE);
lytEmpty.setVisibility(View.VISIBLE);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_sms_list, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
}
return true;
}
private static DiffUtil.ItemCallback<Message> DIFF_CALLBACK =
new DiffUtil.ItemCallback<Message>() {
#Override
public boolean areItemsTheSame(Message oldItem, Message newItem) {
return oldItem.uid == newItem.uid;
}
#Override
public boolean areContentsTheSame(Message oldItem, #NonNull Message newItem) {
return oldItem.equals(newItem);
}
};
}
There are currently 25 elements in the message table but only 20 are displayed at initialization. When I scroll the Recyclerview nothing happens the other 5 elements are not displayed
You need to do like this, I think.
recyclerView.setNestedScrollingEnabled(true);
credit
See here:
https://github.com/googlesamples/android-architecture-components/issues/215#issuecomment-394849133

Data is not updated promptly after adding the information using Realm in Android

I have implement Realm database in my App. At first I want to show some prelod data. Till now I have only three data here. I have implement a dialog fragment which I used to add data in Realm database. I have read the official documentation of Realm. But the implementation of Adapter class is so complecated for me. Hence I have used RecyclerView.Adapter in my Adpater class. Now the problem I am facing that After adding the information the data is not showing promptly.The data is not upadted quickly. it is showing after clicking the add button again. I cannot identify what would be the problem in this case. Also I am happy if someone provide me suggessstion if the writing of this code is not good. Sorry for my bad English.
Edited Adapter Class
Here is my Adpater class
public class PersonAdapter extends RealmRecyclerViewAdapter<PersonModel, PersonAdapter.PersonHolder> {
private RealmResults<PersoneModel> realmResults;
private List<PersonModel> personModels;
private Context context;
public interface PersonListListener {
void addPerson(PersonModel personModel);
void editPerson(PersonModel personModel);
}
public PersonAdapter(Context context,RealmResults<PersonModel> realmResults) {
this.realmResults = realmResults;
this.context = context;
}
// create new views (invoked by the layout manager)
#Override
public PersonHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// inflate a new person view
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.colleage_row_layout,parent,false);
return new PersonHolder(view);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
// get the colleague
final PersonModel person=realmResults.get(position);
// cast the generic view holder to the specific one
final PersonHolder holder = (PersonHolder) viewHolder;
holder.name.setText(person.getName());
holder.companye.setText(person.getCompany());
holder.title.setText(person.getTitle());
holder.cardView.setTag(position);
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//editDataInterface.editData(view,position);
int pos = (int)view.getTag();
Intent i=new Intent(context,DetailPerson.class);
i.putExtra("name",person.getName());
i.putExtra("company",person.getCompany());
i.putExtra("title",person.getTitle());
context.startActivity(i);
}
});
}
// return the size of your data set (invoked by the layout manager)
public int getItemCount() {
return realmResults.size();
}
public class PersonHolder extends RecyclerView.ViewHolder{
public CardView cardView;
public ImageView picture;
public TextView name;
public TextView company;
public TextView title;
public ColleagueHolder(View itemView) {
super(itemView);
name=(TextView)itemView.findViewById(R.id.person_name);
company=(TextView) itemView.findViewById(R.id.company_name);
title=(TextView) itemView.findViewById(R.id.job_title);
cardView=(CardView)itemView.findViewById(R.id.cardview_user);
}
}
}
Edited Activity Calss My Activity class is
public class MainActivity extends AppCompatActivity implements PersonAdapter.PersonListListener{
private RecyclerView recyclerView;
private PersonAdapter adapter;
private Realm personRealm;
private List<PersonModel> personObject;
private RealmResults<PersonModel> dataResult;
private static final String DIALOG_TAG = "EmployeeDialog";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mycolleagues_layout);
// Showing and Enabling clicks on the Home/Up button
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
personRealm = Realm.getDefaultInstance();
recyclerView = (RecyclerView) findViewById(R.id.person_recycler);
setUpRecycler();
if (!Prefs.with(this).getPreLoad()) {
setRealmData();
}
showAllPersons();
}
private void showAllPersons() {
dataResult = personRealm.where(PersonModel.class).findAll();
setAdapter(dataResult);
adapter.notifyDataSetChanged();
}
private void setAdapter(RealmResults<PersonModel> results) {
adapter = new PersonAdapter(this, results);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
private void setUpRecycler() {
// 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 since the cards are vertically scrollable
final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
}
private void setRealmData(){
List<MyColleagueModel> colleague = new ArrayList<>();
MyColleagueModel model = new MyColleagueModel();
model.setId(1 + System.currentTimeMillis());
model.setName("Name1");
model.setCompany("Comapny1");
model.setTitle("Title1");
colleague.add(model);
model = new MyColleagueModel();
model.setId(2 + System.currentTimeMillis());
model.setName("Name2");
model.setCompany("Comapny2");
model.setTitle("Title1");
colleague.add(model);
model = new MyColleagueModel();
model.setId(3 + System.currentTimeMillis());
model.setName("Name3");
model.setCompany("Comapny3");
model.setTitle("Title3");
colleague.add(model);
for (MyColleagueModel realmModel : colleague) {
// Persist the colleague data
colleagueRealm.beginTransaction();
colleagueRealm.copyToRealm(realmModel);
colleagueRealm.commitTransaction();
}
Prefs.with(this).setPreLoad(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.recycler_menu, menu);
final MenuItem item = menu.findItem(R.id.search);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == android.R.id.home) {
finish();
}
//onOptionsItemSelected(MenuItem item) add will open dialog box, which allows user to fill required data
if (id == R.id.addColleague) {
showAlertDialog();
return true;
}
return super.onOptionsItemSelected(item);
}
private void showAlertDialog() {
EditColleagueFragment dialog = new EditColleagueFragment();
//dialog.setPositiveButtonClickListener(this);
dialog.show(getSupportFragmentManager(), DIALOG_TAG);
//adapter.notifyDataSetChanged();
}
#Override
protected void onDestroy() {
if (colleagueRealm!= null)
colleagueRealm.close();
super.onDestroy();
}
/*#Override
public void onSaved() {
dataResult = colleagueRealm.where(MyColleagueModel.class).findAll();
setAdapter(dataResult);
adapter.notifyDataSetChanged();
}*/
#Override
public void addPerson(MyColleagueModel colleagueModel) {
}
#Override
public void editPerson(MyColleagueModel colleagueModel) {
}
}
Using realm-android-adapters:
dependencies {
compile 'io.realm:android-adapters:2.1.0'
}
You need to do
public class MyColleaguesAdapter extends RealmRecyclerViewAdapter<MyColleagueModel, MyColleaguesAdapter.ColleagueHolder> {
public interface ColleagueListListener {
void addPerson(MyColleagueModel colleagueModel);
void editPerson(MyColleagueModel colleagueModel);
}
private final ColleagueListListener colleagueListListener;
public MyColleaguesAdapter(ColleagueListListener colleagueListListener, RealmResults<MyColleagueModel> results) {
super(results, true);
this.colleagueListListener = colleagueListListener;
}
#Override
public ColleagueHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ColleagueHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.colleage_row_layout,parent,false));
}
#Override
public void onBindViewHolder(ColleagueHolder holder, int position) {
final MyColleagueModel myColleague = getData().get(position);
holder.bind(myColleague);
}
public class ColleagueHolder extends RecyclerView.ViewHolder {
public CardView cardView;
public ImageView colleaguePicture;
public TextView colleagueName;
public TextView companyName;
public TextView jobTitle;
private MyColleagueModel myColleague;
private final View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View view) {
colleagueListListener.editPerson(myColleague);
}
}
public ColleagueHolder(View itemView) {
super(itemView);
//colleaguePicture=(ImageView)itemView.findViewById(R.drawable.profile_image);
colleagueName=(TextView)itemView.findViewById(R.id.colleague_name);
companyName=(TextView) itemView.findViewById(R.id.company_name);
jobTitle=(TextView) itemView.findViewById(R.id.job_title);
cardView=(CardView)itemView.findViewById(R.id.cardview_user);
}
}
public void bind(MyColleagueModel myColleague) {
this.myColleague = myColleague;
holder.colleagueName.setText(myColleague.getName());
holder.companyName.setText(myColleague.getCompany());
holder.jobTitle.setText(myColleague.getTitle());
holder.cardView.setTag(position);
holder.cardView.setOnClickListener(listener);
}
}
and
public class MyColleaguesPage extends AppCompatActivity implements MyColleaguesAdapter.ColleagueListListener {
private Realm realm;
private RecyclerView recyclerView;
private MyColleaguesAdapter adapter;
private static final String DIALOG_TAG = "EmployeeDialog";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mycolleagues_layout);
// Showing and Enabling clicks on the Home/Up button
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
realm = Realm.getDefaultInstance();
recyclerView = (RecyclerView) findViewById(R.id.colleagues_recycler);
recyclerView.setHasFixedSize(true);
final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
adapter = new MyColleaguesAdapter(this, realm.where(MyColleagueModel.class).findAllSortedAsync("id"));
recyclerView.setAdapter(adapter);
}
#Override
protected void onDestroy() {
super.onDestroy();
realm.close();
realm = null;
}
}
Step 1:
Inside EditColleagueFragment create interface
public interface onSaveClickListener {
void onSaved()
}
private onSaveClickListener mSaveClickListener;
public void setPositiveButtonClickListener(onSaveClickListener listener){
mSaveClickListener=listener;
}
Step 2: Inside MyColleaguesPage
implement onSaveClickListener
#Override
void onSaved(){
dataResult = colleagueRealm.where(MyColleagueModel.class).findAll();
setAdapter(dataResult);
adapter.notifyDataSetChanged();
}
private void showAlertDialog() {
EditColleagueFragment dialog = new EditColleagueFragment();
dialog.setPositiveButtonClickListener(this)
dialog.show(getSupportFragmentManager(), DIALOG_TAG);
}
Step 3 :
inside
void savePerson(){
-----
---
mSaveClickListener.onSaved();
}

How to take textview data from recycler view to another activity?

I want to take textview data from recycler view to another activity.I want to take
workshop_name TextView to Otheractivity.
Here is my code.
MechSearchActivity.java
public class MechSearchActivity extends AppCompatActivity {
List<SearchResponse.WorkshopDataBean> workshopList;
RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_mec);
recyclerView = (RecyclerView) findViewById(R.id.rv_workshoplist);
callSearchApi();
onItemClick();
}
public void callSearchApi() {
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<SearchResponse> call = apiService.getSearchData( "workshop_name","image", "street", "locality", "city"); // single search for all the values
call.enqueue(new Callback<SearchResponse>() {
#Override
public void onResponse(Call<SearchResponse> call, retrofit2.Response<SearchResponse> response) {
SearchResponse searchResponse = response.body();
workshopList = searchResponse.getWorkshopData();
MechanicRecyclerAdapter adapter = new MechanicRecyclerAdapter(MechSearchActivity.this, workshopList);
recyclerView.setAdapter(adapter);
LinearLayoutManager mGridLayoutManager = new LinearLayoutManager(MechSearchActivity.this); // (Context context, int spanCount)
recyclerView.setLayoutManager(mGridLayoutManager);
}
#Override
public void onFailure(Call<SearchResponse> call, Throwable t) {
}
});
}
private void onItemClick() {
final GestureDetector mGestureDetector = new GestureDetector(MechSearchActivity.this, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
recyclerView_ws.addOnItemTouchListener(new
RecyclerView.OnItemTouchListener() {
#Override
public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
View child = recyclerView.findChildViewUnder(motionEvent.getX(), motionEvent.getY());
if (child != null && mGestureDetector.onTouchEvent(motionEvent)) {
int position = recyclerView.getChildPosition(child);
String workshop_name = workshopList.get(position).getWorkshop_name();
Intent intent = new Intent(MechSearchActivity.this, OtherActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.putExtra("workshop_name", workshop_name);
startActivity(intent);
return true;
}
return false;
}
#Override
public void onTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
}
}
MechRecyclerAdapter.java
public class MechanicRecyclerAdapter extends RecyclerView.Adapter<MechanicRecyclerAdapter.MyViewHolder> {
private static final String TAG = MechanicRecyclerAdapter.class.getSimpleName();
Context mContext;
private LayoutInflater inflater;
String vehicle_type;
List<SearchResponse.WorkshopDataBean> workshopList;
public MechanicRecyclerAdapter(Context context, List<SearchResponse.WorkshopDataBean> workshopList) {
inflater = LayoutInflater.from(context);
this.workshopList = workshopList;
mContext = context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.single_workshop, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
SearchResponse.WorkshopDataBean current = workshopList.get(position);
String ws_name = workshopList.get(position).getWorkshop_name();
holder.tv_workshopname.setText(ws_name);
}
#Override
public int getItemCount() {
return workshopList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
SearchResponse.WorkshopDataBean current;
TextView tv_workshopname;
public MyViewHolder(View itemView) {
super(itemView);
tv_workshopname = (TextView) itemView.findViewById(workshop_name);
}
}
}
OtherActivity.java
public class OtherActivity extends AppCompatActivity {
TextView SingleWorkshopName;
String workshop_name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.otheractivity);
SingleWorkshopName=(TextView)findViewById(R.id.single_workshop_name);
Bundle extras = getIntent().getExtras();
workshop_name = extras.getString("workshop_name", null);
}
}
For that you need to create one interface in your MechanicRecyclerAdapter
public interface OnListItemClick {
void onItemClick(int position);
}
in onBindViewHolder() assign your click by using following code
viewHolder.main_layout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onListItemClick.onItemClick(position);
}
});
Implements this interface in you MechSearchActivity you will get onItemClick() method in your activity using position you will get proper name of row and pass to other activity using intent.putExtra("workshop_name", workshop_name);

Calling setAdapter on Fragment (Recycler View) not working

I tried to set the adapter on fragment, but nothing shows up.
The object retrieves the data from API but doesn't show on the screen.
I have already put the break point on rvItem.setAdapter(mainAdapter); but nothings happen, the debug passes straight through.
public class ItemFragment extends Fragment {
private MainAdapter mainAdapter;
private ItemPresenter itemPresenter;
private GridLayoutManager mLayoutManager;
private List<ObjectAdapter> list = new ArrayList<>();
private String region = "br";
#Bind(R.id.rvItem)
RecyclerView rvItem;
public ItemFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_item, container, false);
ButterKnife.bind(this, view);
itemPresenter = new ItemPresenter();
mLayoutManager = new GridLayoutManager(getActivity(), 4);
rvItem.setLayoutManager(mLayoutManager);
getList();
return view;
}
private void getList() {
itemPresenter.loadItemList(region, "all", AppConfigs.api_key, new ItemListListener() {
#Override
public void onRequestStarted() {
}
#Override
public void onRequestFinished() {
}
#Override
public void onError(Throwable error) {
}
#Override
public void onItemListLoad(List<ItemDto> itemList) {
displayItemList(ObjectAdapter.convertItemToObjetct(itemList));
}
});
}
public void displayItemList(List<ObjectAdapter> itemList) {
list = itemList;
mainAdapter = new MainAdapter(getActivity(), list, new MainAdapter.OnObjectClickListener() {
#Override
public void OnObjectClickListener(ObjectAdapter objectAdapter) {
Toast.makeText(getActivity(), "Object Adapter" + objectAdapter.Id, Toast.LENGTH_SHORT).show();
}
});
rvItem.setAdapter(mainAdapter);
mainAdapter.notifyDataSetChanged();
}
}
Adapter:
public class MainAdapter extends
RecyclerView.Adapter<MainAdapter.MainAdapterViewHolder> {
public List<ObjectAdapter> mObjecterList;
private final OnObjectClickListener listener;
private Context mContext;
public interface OnObjectClickListener {
void OnObjectClickListener(ObjectAdapter objectAdapter);
}
public MainAdapter(Context context, List<ObjectAdapter> objectAdapterList, OnObjectClickListener listener) {
this.mObjecterList = objectAdapterList;
this.listener = listener;
this.mContext = context;
}
#Override
public MainAdapter.MainAdapterViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_main_adapter, parent, false);
return new MainAdapterViewHolder(view);
}
#Override
public void onBindViewHolder(MainAdapter.MainAdapterViewHolder holder, int position) {
ObjectAdapter ob = mObjecterList.get(position);
holder.tvNameText.setText(ob.Name);
holder.bind(mObjecterList.get(position), listener);
String url = "";
switch (ob.Type){
case CHAMPION: url = String.format(AppConfigs.portraitChampion, ob.Portrait);
break;
case SPELL: url = String.format(AppConfigs.portraitSpell, ob.Portrait);
break;
case ITEM: url = String.format(AppConfigs.portraitItem, ob.Portrait);
break;
}
Picasso.with(mContext).load(url).into(holder.ivRetrato);
}
#Override
public int getItemCount() {
return this.mObjecterList.size();
}
public static class MainAdapterViewHolder extends RecyclerView.ViewHolder {
public TextView tvNameText;
public ImageView ivRetrato;
public MainAdapterViewHolder(View itemView) {
super(itemView);
this.tvNameText = (TextView) itemView.findViewById(R.id.tvNameText);
this.ivRetrato = (ImageView) itemView.findViewById(R.id.ivImagePortrait);
}
public void bind(final ObjectAdapter objectAdapterListItem, final OnObjectClickListener listener) {
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.OnObjectClickListener(objectAdapterListItem);
}
});
}
}
}
You need to set adapter directly at onCreateView method and call notifyDataSetChanged() of adapter when data loaded

RX Java RecycleView

I'm not familiar with rx java. Trying to use it with recycleview. For some reason my code is not working Here is my code.
Fragment with recycle view
public class CheeseListFragment extends Fragment {
private final CompositeSubscription subscriptions = new CompositeSubscription();
private PublishSubject<String> timespanSubject;
private final Func1<String, Observable<LiveInfo>> trendingSearch =
new Func1<String, Observable<LiveInfo>>() {
#Override
public Observable<LiveInfo> call(String s) {
RadioLiveInfoObservableService radioLiveInfoObservableService=ApiProvider.getInstance().getRadioObserverInfo();
return radioLiveInfoObservableService.radioInfo(Type.INTERVAL)
.observeOn(AndroidSchedulers.mainThread())
.doOnError(trendingError)
.onErrorResumeNext(Observable.<LiveInfo>empty());
}
};
private final Action1<Throwable> trendingError = new Action1<Throwable>() {
#Override public void call(Throwable throwable) {
Timber.e(throwable, "Failed to get trending repositories");
}
};
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
timespanSubject = PublishSubject.create();
final RecyclerView rv = (RecyclerView) inflater.inflate(
R.layout.fragment_cheese_list, container, false);
setupRecyclerView(rv);
subscriptions.add(timespanSubject
.flatMap(trendingSearch)
.map(SearchResultToRepositoryList.instance())
.subscribe(adapter));
return rv;
}
private SimpleStringRecyclerViewAdapter adapter;
private void setupRecyclerView(RecyclerView recyclerView) {
recyclerView.setLayoutManager(new LinearLayoutManager(recyclerView.getContext()));
adapter=new SimpleStringRecyclerViewAdapter(getActivity(), new SimpleStringRecyclerViewAdapter.CurrentShowClickListener() {
#Override
public void onCurrentShowClick(Current currentShow) {
Intent intent = new Intent(CApplication.getAppContext(), CheeseDetailActivity.class);
intent.putExtra(CheeseDetailActivity.EXTRA_NAME, currentShow.getName());
CApplication.getAppContext().startActivity(intent);
}
});
recyclerView.setAdapter(adapter);
adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
#Override
public void onChanged() {
Toast.makeText(getActivity(),"data changed",Toast.LENGTH_SHORT).show();
}
});
}
private List<String> getRandomSublist(String[] array, int amount) {
ArrayList<String> list = new ArrayList<>(amount);
Random random = new Random();
while (list.size() < amount) {
list.add(array[random.nextInt(array.length)]);
}
return list;
}
public static class SimpleStringRecyclerViewAdapter
extends RecyclerView.Adapter<SimpleStringRecyclerViewAdapter.ViewHolder> implements Action1<List<Current>> {
private List<Current> currentShows = Collections.emptyList();
public interface CurrentShowClickListener {
void onCurrentShowClick(Current currentShow);
}
private final CurrentShowClickListener currentShowClickListener;
private final TypedValue mTypedValue = new TypedValue();
private int mBackground;
#Override
public void call(List<Current> currentShows) {
this.currentShows = currentShows;
notifyDataSetChanged();
}
public SimpleStringRecyclerViewAdapter(Context context,CurrentShowClickListener currentShowClickListener) {
context.getTheme().resolveAttribute(R.attr.selectableItemBackground, mTypedValue, true);
mBackground = mTypedValue.resourceId;
this.currentShowClickListener = currentShowClickListener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
ListItemView view = (ListItemView)LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item, parent, false);
view.setBackgroundResource(mBackground);
return new ViewHolder(view);
}
#Override public void onBindViewHolder(ViewHolder viewHolder, int i) {
viewHolder.bindTo(currentShows.get(i));
}
#Override public long getItemId(int position) {
return position;
}
#Override public int getItemCount() {
return currentShows.size();
}
public final class ViewHolder extends RecyclerView.ViewHolder {
public final ListItemView itemView;
private Current currentShow;
public ViewHolder(ListItemView itemView) {
super(itemView);
this.itemView = itemView;
this.itemView.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
currentShowClickListener.onCurrentShowClick(currentShow);
}
});
}
public void bindTo(Current currentShow) {
this.currentShow = currentShow;
itemView.bindTo(currentShow);
}
}
}
}
SearchToResultRepositoryList
public final class SearchResultToRepositoryList implements Func1<LiveInfo, List<Current>> {
private static volatile SearchResultToRepositoryList instance;
public static SearchResultToRepositoryList instance() {
if (instance == null) {
instance = new SearchResultToRepositoryList();
}
return instance;
}
#Override public List<Current> call(LiveInfo repositoriesResponse) {
List<Current> currents=new ArrayList<>();
currents.add(repositoriesResponse.getCurrent());
return currents;
}
}
REST
public interface RadioLiveInfoObservableService {
#GET("/api/live-info/")
Observable<LiveInfo> radioInfo(
#Query("type") Type type);
}
It's just doing nothing. I tried to debug it trendingSearch.call is not called at all.
I can make it work only this way. But still i want to know how to it with subscription
RadioLiveInfoObservableService radioLiveInfoObservableService=ApiProvider.getInstance().getRadioObserverInfo();
radioLiveInfoObservableService.commits(Type.INTERVAL)
.observeOn(AndroidSchedulers.mainThread())
.doOnError(trendingError)
.onErrorResumeNext(Observable.<LiveInfo>empty()).subscribe(new Action1<LiveInfo>() {
#Override
public void call(LiveInfo liveInfo) {
List<Current> currents=new ArrayList<Current>();
currents.add(liveInfo.getCurrent());
adapter.currentShows=currents;
adapter.notifyDataSetChanged();
rv.setAdapter(adapter);
}
});
That's a lot of code to digest looking for errors, but off the top of my head nothing will happen until timeSpanSubject.onNext() is called. I don't see this called anywhere but maybe there is some missing code you are not showing.
If there is no missing code that calls timeSpanSubject.onNext(), then you could use either a BehaviorSubject which will emit an item when first subscribed to or another Observable such as timer or interval depending on what you are trying to do. timer would subscribe to your trendingSearch Observable a single time whereas using an interval would subscribe multiple times.

Categories

Resources