how to make Recyclerview works correctly with callback - android

i have implemented recyclerview and it works fine , i used a call back in BikeAdapter to be able to click every single row of this recycler view but when, i put these lines in OnCreateView the recycler view recycler throw null callback error , and when i delete mAdapter.setCallback(this); the recyclerview became empty
recyclerView.setAdapter(mAdapter); fillData();
mAdapter = new BikesAdapter(getActivity(), (ArrayList<Bike>) bikes);
mAdapter.setCallback(this);
and when i put these lines inside the filldata() OnResponse method : mAdapter.setCallback(this) is not recognized
mAdapter.setCallback(this);
if i want to display my recycler view without problems i have to delete mAdapter.setCallback(this);
mAdapter = new BikesAdapter(getActivity(), (ArrayList) bikes);
recyclerView.setAdapter(mAdapter);
inside the fillData to get the response at the right time
//my adapter code
package com.example.miniprojetandroid.adapters;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.miniprojetandroid.R;
import com.example.miniprojetandroid.models.Bike;
public class BikesAdapter extends RecyclerView.Adapter<BikesAdapter.BikesViewHolder> {
private final ArrayList<Bike> bikes;
private Context mContext;
private Callback mCallback;
public BikesAdapter(Context mContext, ArrayList<Bike> bikes) {
this.mContext = mContext ;
this.bikes = bikes;
}
#NonNull
#Override
public BikesAdapter.BikesViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View mItemView = LayoutInflater.from(mContext).inflate(R.layout.bike_list_item, parent, false);
return new BikesViewHolder(mItemView, this);
}
#Override
public void onBindViewHolder(#NonNull BikesAdapter.BikesViewHolder holder, int position) {
final Bike singleItem = bikes.get(position);
holder.BikeName.setText(singleItem.getModel());
holder.BikeImage.setBackgroundResource(singleItem.getImage());
holder.bikeView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCallback.onItemClicked(singleItem);
}
});
holder.BikeImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext,singleItem.getModel(),Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return bikes.size();
}
public class BikesViewHolder extends RecyclerView.ViewHolder {
public final TextView BikeName;
public final ImageView BikeImage;
public final Button bikeView;
final BikesAdapter mAdapter;
public BikesViewHolder(#NonNull View itemView, BikesAdapter mAdapter) {
super(itemView);
this.BikeName = itemView.findViewById(R.id.bikeName);
this.BikeImage = itemView.findViewById(R.id.bikeImage);
this.bikeView = itemView.findViewById(R.id.btn_view);
this.mAdapter = mAdapter;
}
}
public void setCallback(Callback callback) {
mCallback = callback;
}
public interface Callback {
void onItemClicked(Bike bike);
}
}
//my fragment that contains the recyclerview
package com.example.miniprojetandroid.ui.fragments;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.miniprojetandroid.R;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.miniprojetandroid.Retrofit.BikeService;
import com.example.miniprojetandroid.Retrofit.RetrofitClient;
import com.example.miniprojetandroid.Retrofit.UserService;
import com.example.miniprojetandroid.adapters.BikesAdapter;
import com.example.miniprojetandroid.models.Bike;
import com.example.miniprojetandroid.models.User;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class FragmentOne extends Fragment implements BikesAdapter.Callback{
private BikeService apiService;
private RecyclerView recyclerView;
private List<Bike> bikes = new ArrayList<Bike>();
private BikesAdapter mAdapter;
List<Bike> result = new ArrayList<Bike>();
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_one, container,false);
recyclerView = rootView.findViewById(R.id.recycler_bikes);
recyclerView.setHasFixedSize(true);
recyclerView.setNestedScrollingEnabled(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(),
LinearLayoutManager.VERTICAL, false));
apiService = RetrofitClient.getClient().create(BikeService.class);
fillData();
mAdapter.setCallback(this);
return rootView;
}
public void fillData(){
Call<List<Bike>> call = apiService.getBikes();
call.enqueue(new Callback<List<Bike>>() {
#Override
public void onResponse(Call<List<Bike>> call, Response<List<Bike>> response) {
if(response.isSuccessful()){
bikes.addAll(response.body());
for(Bike bike: bikes){
bike.setImage(R.drawable.ruebike);
}
Log.e("Bike LIST", bikes.toString());
mAdapter = new BikesAdapter(getActivity(), (ArrayList<Bike>) bikes);
recyclerView.setAdapter(mAdapter);
//listView.setAdapter(new UserAdapter(MainActivity.this, R.layout.list_user, list));
}
}
#Override
public void onFailure(Call<List<Bike>> call, Throwable t) {
Log.e("ERROR: ", t.getMessage());
}
});
/*bikes.add(new Bike(1,"ECO", "RTT" , "44", R.drawable.ruebike ));
bikes.add(new Bike(2,"AAA", "RTT" , "33", R.drawable.ruebike ));
bikes.add(new Bike(3,"BBB", "RUE" , "11", R.drawable.ruebike ));
bikes.add(new Bike(4,"EEE", "SPORT" , "25", R.drawable.ruebike ));
bikes.add(new Bike(5,"CCC", "SPORT" , "77", R.drawable.ruebike ));
Log.e("USERS LIST", bikes.toString());*/
}
#Override
public void onItemClicked(Bike bike) {
Bundle bundle = new Bundle();
bundle.putInt("bike_id",bike.getId());
bundle.putString("model", bike.getModel());
bundle.putString("type", bike.getType());
bundle.putString("price", bike.getPrice());
bundle.putInt("image", bike.getImage());
DetailsFragment f = new DetailsFragment();
f.setArguments(bundle);
getActivity().getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragmentsContainer, f )
.commit();
}
}
What i am trying to do is two things:
1/ make my fragment recyclerview works with filldata with the call back method(for idea Log.e show that this method works fine)
2/ to make sure that when i click an item of the recycler view , i pass the selected bike to a thired fragmend (DetailsFragment)
Errors: the recycler view is empty when i delete the callback and it throw null exception when i use it
help me pls

the method fillData is not executing immediately because it contain network operation so it work on background thread , so when you call setCallback , the mAdapter will not be initialized yet , so i suggest to initialize mAdapter and call setAdapter inside onCreate instead of onResponse method, and you can pass the array to the constructor as null ,and inside onResponse you can pass the bikes arrayList by setter method and inside this method (the setter method) after assigning the list add "notifyDataSetChanged();"
so your adapter will look like :
package com.example.miniprojetandroid.adapters;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.miniprojetandroid.R;
import com.example.miniprojetandroid.models.Bike;
public class BikesAdapter extends RecyclerView.Adapter<BikesAdapter.BikesViewHolder> {
private final ArrayList<Bike> bikes;
private Context mContext;
private Callback mCallback;
public BikesAdapter(Context mContext, ArrayList<Bike> bikes) {
this.mContext = mContext ;
this.bikes = bikes;
}
public setBikesList(ArrayList<Bike> bikes){
this.bikes=bikes;
notifyDataSetChanged();
}
#NonNull
#Override
public BikesAdapter.BikesViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View mItemView = LayoutInflater.from(mContext).inflate(R.layout.bike_list_item, parent, false);
return new BikesViewHolder(mItemView, this);
}
#Override
public void onBindViewHolder(#NonNull BikesAdapter.BikesViewHolder holder, int position) {
final Bike singleItem = bikes.get(position);
holder.BikeName.setText(singleItem.getModel());
holder.BikeImage.setBackgroundResource(singleItem.getImage());
holder.bikeView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCallback.onItemClicked(singleItem);
}
});
holder.BikeImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext,singleItem.getModel(),Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return bikes.size();
}
public class BikesViewHolder extends RecyclerView.ViewHolder {
public final TextView BikeName;
public final ImageView BikeImage;
public final Button bikeView;
final BikesAdapter mAdapter;
public BikesViewHolder(#NonNull View itemView, BikesAdapter mAdapter) {
super(itemView);
this.BikeName = itemView.findViewById(R.id.bikeName);
this.BikeImage = itemView.findViewById(R.id.bikeImage);
this.bikeView = itemView.findViewById(R.id.btn_view);
this.mAdapter = mAdapter;
}
}
public void setCallback(Callback callback) {
mCallback = callback;
}
public interface Callback {
void onItemClicked(Bike bike);
}
}
and your fragment :
package com.example.miniprojetandroid.ui.fragments;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.miniprojetandroid.R;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.miniprojetandroid.Retrofit.BikeService;
import com.example.miniprojetandroid.Retrofit.RetrofitClient;
import com.example.miniprojetandroid.Retrofit.UserService;
import com.example.miniprojetandroid.adapters.BikesAdapter;
import com.example.miniprojetandroid.models.Bike;
import com.example.miniprojetandroid.models.User;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class FragmentOne extends Fragment implements BikesAdapter.Callback{
private BikeService apiService;
private RecyclerView recyclerView;
private List<Bike> bikes = new ArrayList<Bike>();
private BikesAdapter mAdapter;
List<Bike> result = new ArrayList<Bike>();
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_one, container,false);
recyclerView = rootView.findViewById(R.id.recycler_bikes);
recyclerView.setHasFixedSize(true);
recyclerView.setNestedScrollingEnabled(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(),
LinearLayoutManager.VERTICAL, false));
apiService = RetrofitClient.getClient().create(BikeService.class);
fillData();
mAdapter = new BikesAdapter(getActivity(),null);
mAdapter.setCallback(this);
recyclerView.setAdapter(mAdapter);
return rootView;
}
public void fillData(){
Call<List<Bike>> call = apiService.getBikes();
call.enqueue(new Callback<List<Bike>>() {
#Override
public void onResponse(Call<List<Bike>> call, Response<List<Bike>> response) {
if(response.isSuccessful()){
bikes.addAll(response.body());
for(Bike bike: bikes){
bike.setImage(R.drawable.ruebike);
}
Log.e("Bike LIST", bikes.toString());
mAdapter.setBikesList(bikes);
//listView.setAdapter(new UserAdapter(MainActivity.this, R.layout.list_user, list));
}
}
#Override
public void onFailure(Call<List<Bike>> call, Throwable t) {
Log.e("ERROR: ", t.getMessage());
}
});
/*bikes.add(new Bike(1,"ECO", "RTT" , "44", R.drawable.ruebike ));
bikes.add(new Bike(2,"AAA", "RTT" , "33", R.drawable.ruebike ));
bikes.add(new Bike(3,"BBB", "RUE" , "11", R.drawable.ruebike ));
bikes.add(new Bike(4,"EEE", "SPORT" , "25", R.drawable.ruebike ));
bikes.add(new Bike(5,"CCC", "SPORT" , "77", R.drawable.ruebike ));
Log.e("USERS LIST", bikes.toString());*/
}
#Override
public void onItemClicked(Bike bike) {
Bundle bundle = new Bundle();
bundle.putInt("bike_id",bike.getId());
bundle.putString("model", bike.getModel());
bundle.putString("type", bike.getType());
bundle.putString("price", bike.getPrice());
bundle.putInt("image", bike.getImage());
DetailsFragment f = new DetailsFragment();
f.setArguments(bundle);
getActivity().getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragmentsContainer, f )
.commit();
}
}

Related

How to take reference of itemClick on recyclerview

Suppose I have a scrolling RecyclerView (where images scrolling Horizontally) after clicking any of images it will appear below the recyclerView.
Main Activity:
package com.aariyan.testm;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;`enter code here`
import com.daimajia.slider.library.Animations.DescriptionAnimation;
import com.daimajia.slider.library.Indicators.PagerIndicator;
import com.daimajia.slider.library.SliderLayout;`enter code here`
import com.daimajia.slider.library.SliderTypes.BaseSliderView;
import com.daimajia.slider.library.SliderTypes.TextSliderView;
import com.daimajia.slider.library.Tricks.ViewPagerEx;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
//implements BaseSliderView.OnSliderClickListener, ViewPagerEx.OnPageChangeListener
private SliderLayout mDemoSlider;
private ImageView imageView;
private String selectDrinkCategory;
private String drinks = "drinks";
//String i = "0";
int j;
RecyclerViewAdapter recyclerViewAdapter;
private int[] images = {R.drawable.a,
R.drawable.bb,
R.drawable.c,
R.drawable.d,
R.drawable.e,
R.drawable.d_2_1,
R.drawable.d_2_2,
R.drawable.d_2_3,
R.drawable.d_2_4
};
private ArrayList<Integer> inputImages = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//get Intent
Intent intent = getIntent();
if (getIntent() != null) {
selectDrinkCategory = intent.getStringExtra("drinks");
}
initUI();
initBitmapImages();
initRecyclerView();
Toast.makeText(this, "J: "+j, Toast.LENGTH_SHORT).show();
}
private void initRecyclerView() {
LinearLayoutManager manager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
RecyclerView recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(manager);
RecyclerViewAdapter adapter = new RecyclerViewAdapter(inputImages, this);
Toast.makeText(this, " Main Value j : " + adapter.index, Toast.LENGTH_SHORT).show();
imageView.setImageResource(images[j]);
recyclerView.setAdapter(adapter);
}
private void initBitmapImages() {
for (int i = 0; i < images.length; i++) {
// inputImages.add(String.valueOf(images[i]));
inputImages.add(images[i]);
}
}
private void initUI() {
//mDemoSlider = (SliderLayout) findViewById(R.id.slider);
imageView = findViewById(R.id.viewSingleImages);
//imageView.setImageResource((images[0]));
}
#Override
protected void onStop() {
// To prevent a memory leak on rotation, make sure to call stopAutoCycle() on the slider before activity or fragment is destroyed
super.onStop();
}
}
RecyclerView:
I have a scrolling RecyclerView (where images scrolling Horizontally) after clicking any of images it will appear below the
package com.aariyan.testm;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
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.Toast;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
private ArrayList<Integer> totalImages = new ArrayList<>();
private Context context;
//MainActivity mainActivity;
int index = 0;
public RecyclerViewAdapter(ArrayList<Integer> totalImages, Context context) {
this.totalImages = totalImages;
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.images, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder viewHolder, final int i) {
//index = 0;
Glide.with(context).asBitmap().load(totalImages.get(i)).into(viewHolder.singleImages);
viewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isClicked) {
Toast.makeText(context, "TotalImages : "+totalImages.get(i), Toast.LENGTH_SHORT).show();
index = totalImages.get(i);
}
});
// viewHolder.singleImages.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// Toast.makeText(context, "" + viewHolder.getAdapterPosition(), Toast.LENGTH_SHORT).show();
// //viewHolder.imageView.setImageResource(totalImages.get(viewHolder.getAdapterPosition()));
// //index = viewHolder.getAdapterPosition();
// index = i;
// Toast.makeText(context, "Index : " + index, Toast.LENGTH_SHORT).show();
// }
// });
}
#Override
public int getItemCount() {
return totalImages.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public ImageView singleImages;
private ItemClickListener itemClickListener;
public ViewHolder(#NonNull View itemView) {
super(itemView);
singleImages = itemView.findViewById(R.id.imagesViewOnScroll);
itemView.setOnClickListener(this);
}
public void setItemClickListener (ItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
#Override
public void onClick(View v) {
itemClickListener.onClick(v,getAdapterPosition(),false);
}
}
}
activity_main.xml : just have a recyclerView and image View
and images.xml : only a image view to set on RecyclerView
for get clicked item of recyckerview you have to use interface.
here is code sample:
first of all make one interface like below :
public interface ImageClickListener {
void onImageClick(String path);
}
now in your activity, make adapter's object like this
RecyclerViewAdapter adapter = new RecyclerViewAdapter(inputImages, this, new ImageClickListener() {
#Override
public void onImageClick(String path) {
Glide.with(context).load(path).into(imageView);
}
});
now create your adapter and make a constructor like this
public RecyclerViewAdapter(ArrayList<Integer> totalImages, Context context, ImageClickListener imageClickListener) {
this.totalImages = totalImages;
this.context = context;
this.imageClickListener = imageClickListener;
}
now you have an instance of interface in which you have one method, named onImageClick() in which you will pass the path of clicked image.
now on click of image do code like this:
viewHolder.singleImages.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imageClickListener.onImageClick(totalImages.get(viewHolder.getAdapterPosition()));
}
});
now your method of interface will call & it will execute activity's image view to set the given path.
Enjoy codding :)

Reload a RecyclerView after deleting some rows from a table

So when I delete a row in the SQLITE Database and the actual activity is closing, I see the CardView which is delete.
I really tried to google but nothing changed, so maybe you could help me out guys.
This is the SQLITE Delete function:
public void deleteEntry(String ID){
SQLiteDatabase db = this.getWritableDatabase();
String query = "DELETE FROM " + DB_NAME + " WHERE ID = '" + ID + "'";
Log.d("QUERY",query);
db.execSQL(query);
db.close();
}
MyAdapter.java
package simplylabs.com.simplynote;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import static android.content.ContentValues.TAG;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder>
{
public MyAdapter(List<ListItem> listItems, Context context) {
this.listItems = listItems;
this.context = context;
}
private List<ListItem> listItems;
private Context context;
#Override
public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.row_design,parent,false);
return new MyViewHolder(v);
}
#Override
public void onBindViewHolder(MyAdapter.MyViewHolder holder, int position)
{
final ListItem list = listItems.get(position);
holder.insert_NOTIZENNAME.setText(list.getNOTIZENNAME());
holder.insert_NOTIZ.setText(list.getNOTIZ());
holder.insert_TIME.setText(list.getTIME());
if(list.getPRIORITAET().equals("Sehr wichtig")){
holder.prioColor.setBackgroundResource(R.color.rot);
}
if(list.getPRIORITAET().equals("Wichtig")){
holder.prioColor.setBackgroundResource(R.color.orange);
}
if(list.getPRIORITAET().equals("Nicht wichtig")){
holder.prioColor.setBackgroundResource(R.color.gruen);
}
}
#Override
public int getItemCount() {
return listItems.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder{
TextView insert_NOTIZENNAME;
TextView insert_NOTIZ;
TextView insert_TIME;
View prioColor;
public MyViewHolder(View itemView) {
super(itemView);
insert_NOTIZENNAME = itemView.findViewById(R.id.showNOTIZENNAME);
insert_NOTIZ = itemView.findViewById(R.id.show_NOTIZ);
insert_TIME = itemView.findViewById(R.id.show_DATUM);
prioColor = itemView.findViewById(R.id.view_prioritaet);
}
}
}
This is when I click on the menu Item:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
DBHandler dbHandler = new DBHandler(this);
final Bundle extras = getIntent().getExtras();
switch(item.getItemId()){
case R.id.notiz_loeschen:
dbHandler.deleteEntry(extras.getString("ID"));
Toast.makeText(this, extras.getString("ID"), Toast.LENGTH_SHORT).show();
finish();
break;
case R.id.notiz_aendern:
break;
}
return super.onOptionsItemSelected(item);
}
MainActivity.java
recyclerView = rootView.findViewById(R.id.recyclerview_alle_notizen);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setItemAnimator(new DefaultItemAnimator());
adapter = new MyAdapter(listItems,getActivity());
adapter.notifyDataSetChanged();
recyclerView.setAdapter(adapter);
recyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(getActivity(), new RecyclerItemClickListener.OnItemClickListener() {
#Override public void onItemClick(View view, int position) {
if (data.moveToPosition(position))
{
Intent i = new Intent(getActivity(),NotizAnzeigen.class);
i.putExtra("NotizName",data.getString(1));
i.putExtra("Notiz",data.getString(2));
startActivity(i);
}
}
})
);
Could you please help me out please?
I've changed this, it is still only remove the cardview when i move to the last tab ...
package simplylabs.com.simplynote;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
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 android.widget.Button;
import java.util.ArrayList;
import java.util.List;
public class AlleNotizen extends Fragment {
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
private List<ListItem> listItems;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.alle_notizen, container, false);
recyclerView = rootView.findViewById(R.id.recyclerview_alle_notizen);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setItemAnimator(new DefaultItemAnimator());
return rootView;
}
#Override
public void onResume() {
listItems = new ArrayList<>();
ListItem listItem = new ListItem();
final DBHandler db = new DBHandler(getActivity());
final Cursor data = db.getData();
while(data.moveToNext()){
ListItem li = new ListItem(data.getString(0), data.getString(1),data.getString(2),data.getString(4),data.getString(3));
listItems.add(li);
}
adapter = new MyAdapter(listItems,getActivity());
adapter.notifyDataSetChanged();
recyclerView.setAdapter(adapter);
recyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(getActivity(), new RecyclerItemClickListener.OnItemClickListener() {
#Override public void onItemClick(View view, int position) {
if (data.moveToPosition(position))
{
Intent i = new Intent(getActivity(),NotizAnzeigen.class);
i.putExtra("NotizName",data.getString(1));
i.putExtra("Notiz",data.getString(2));
startActivity(i);
}
}
})
);
super.onResume();
}
}
As you are deleting data from your local storage you need to notify the adapter that data set has changed.To do that you could try this.
After deleting data from SQLite you need to read data again and store
it in a list/arraylist variable.
create a function inside your adapter like this,
public void loadWithNewData(List<items> newCollectedData) {
this.listItems.clear();
this.listItems = newCollectedData;
this.notifyDataSetChanged();
}
And then call that function with adapter variable like this.
adapter.loadWithNewData(newDataCollectedFromDatabase);
hope it will help.
You are deleting the row from the database, but you are not updating your listItems array. You should update listItems and then call adapter.notifyDataSetChanged();

Displaying a list of items that are stored on shared preferences

I have a recyclerview with a couple of items. When someone clicks on an item in the Main Fragment, it is stored on sharedpreferences and then all clicked items are supposed to be displayed on another fragment. My issue is when someone clicks on an item, only the first clicked item is displayed on the other fragment(Details Fragment) instead of a list of items.
These are the methods of saving, retrieving and removing items on my SessionManager.class
public void saveitems(Context context,List<SingleItem> items){
Gson gson = new Gson();
String cartitems = gson.toJson(items);
editor.putString(KEY_ITEMS,cartitems);
editor.commit();
}
public void grandtotal (String total){
editor.putString(KEY_TOTAL,total);
editor.commit();
}
public void savetocart(Context context, SingleItem singleitems){
List<SingleItem> itemList = getItems(context);
if (itemList == null) {
itemList = new ArrayList<>();
itemList.add(singleitems);
saveitems(context, itemList);
}
}
public ArrayList<SingleItem> getItems(Context context){
List<SingleItem> items;
if (pref.contains(KEY_ITEMS)){
String cartitems = pref.getString(KEY_ITEMS,null);
Gson gson = new Gson();
SingleItem[] singleItems = gson.fromJson(cartitems,SingleItem[].class);
items = Arrays.asList(singleItems);
items = new ArrayList<>(items);
}
else
return null;
return (ArrayList<SingleItem>) items;
}
public void removeitem(Context context, SingleItem singleItem){
ArrayList<SingleItem> items = getItems(context);
if (items != null){
items.remove(singleItem);
saveitems(context,items);
}
}
This is how i am storing the items that have been clicked. Take a look at (RecyclerItems):
package com.carlton.shop;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
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.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import es.dmoral.toasty.Toasty;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import ss.com.bannerslider.banners.RemoteBanner;
import ss.com.bannerslider.views.BannerSlider;
/**
* A simple {#link Fragment} subclass.
*/
public class MainFragment extends Fragment {
private BannerSlider bannerSlider;
private RecyclerView Categories;
public RecyclerView RecyclerItems;
private ShopItemAdapter adapter;
private List<ShopItem> item;
SessionManager sessionManager;
private List<SingleItem> items;
private SingleItemAdapter adapters;
private LinearLayout Layoutcategories, Layoutitems;
private TextView CatName;
private Button Up;
public MainFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_main, container, false);
bannerSlider = (BannerSlider) view.findViewById(R.id.banner_slider1);
Categories = (RecyclerView) view.findViewById(R.id.recyclercategories);
Layoutcategories = (LinearLayout) view.findViewById(R.id.LayoutCategories);
Layoutitems = (LinearLayout) view.findViewById(R.id.LayoutItems);
RecyclerItems = (RecyclerView) view.findViewById(R.id.recycleritems);
CatName = (TextView) view.findViewById(R.id.tvcategoryname);
Up = (Button) view.findViewById(R.id.btnup);
sessionManager = new SessionManager(getContext());
Categories.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
Categories.setLayoutManager(layoutManager);
RecyclerItems.setHasFixedSize(true);
RecyclerView.LayoutManager layoutmanager = new LinearLayoutManager(getContext());
RecyclerItems.setLayoutManager(layoutmanager);
Categories.addOnItemTouchListener(new RecyclerItemClickListener(getContext(), new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
Layoutcategories.setVisibility(View.GONE);
Layoutitems.setVisibility(View.VISIBLE);
sessionManager.createcategorysession(item.get(position).getCategory());
HashMap<String, String> cat = sessionManager.getcategoryitems();
CatName.setText(cat.get(SessionManager.KEY_CATEGORY));
Up.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Layoutitems.setVisibility(View.GONE);
Layoutcategories.setVisibility(View.VISIBLE);
}
});
items = new ArrayList<>(item.get(position).getItems());
adapters = new SingleItemAdapter(getContext(),items);
RecyclerItems.setAdapter(adapters);
RecyclerItems.addOnItemTouchListener(new RecyclerItemClickListener(getContext(), new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
sessionManager.savetocart(getContext(), items.get(position));
Toasty.success(getContext(),"Added to cart",Toast.LENGTH_SHORT,true).show();
}
}));
}
}));
Banner();
getdata();
return view;
}
private void Banner() {
bannerSlider.addBanner(new RemoteBanner("http://supa.swagshop.co.ke/Images/moto.png"));
bannerSlider.addBanner(new RemoteBanner("http://supa.swagshop.co.ke/Images/moto.png"));
bannerSlider.addBanner(new RemoteBanner("http://supa.swagshop.co.ke/Images/moto.png"));
bannerSlider.addBanner(new RemoteBanner("http://supa.swagshop.co.ke/Images/moto.png"));
}
private void getdata() {
final ProgressDialog progressDialog = new ProgressDialog(getContext());
progressDialog.setMessage("Loading Items...");
progressDialog.show();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
InterfaceRequest request = retrofit.create(InterfaceRequest.class);
Call<JSONResponse> call =request.getJSON();
call.enqueue(new Callback<JSONResponse>() {
#Override
public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
if (response.isSuccessful()){
JSONResponse jsonResponse = response.body();
item = new ArrayList<>(jsonResponse.getItem());
adapter = new ShopItemAdapter(getContext(),item);
Categories.setAdapter(adapter);
} else {
Toasty.warning(getContext(),"Oops! Items could not be loaded",Toast.LENGTH_SHORT,true).show();
}
progressDialog.dismiss();
}
#Override
public void onFailure(Call<JSONResponse> call, Throwable t) {
Toasty.error(getContext(),t.getLocalizedMessage(),Toast.LENGTH_SHORT,true).show();
Log.d(Constants.TAG,t.getMessage());
progressDialog.dismiss();
}
});
}
}
This is how i'm retrieving the items on DetailsFragment;
package com.carlton.shop;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import es.dmoral.toasty.Toasty;
import static com.helpshift.util.HelpshiftContext.getApplicationContext;
/**
* A simple {#link Fragment} subclass.
*/
public class Details extends Fragment {
private RecyclerView RecyclerDetails;
private TextView CartPrice;
private CheckBox CheckCart;
private List<SingleItem> list;
private CartAdapter adapter;
private boolean add = false;
private Paint p = new Paint();
private SessionManager sessionManager;
public Details() {
// 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_details, container, false);
RecyclerDetails = (RecyclerView) view.findViewById(R.id.recyclercart);
CartPrice = (TextView) view.findViewById(R.id.tvcart);
CheckCart = (CheckBox) view.findViewById(R.id.chkcart);
sessionManager = new SessionManager(getContext());
RecyclerDetails.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
RecyclerDetails.setLayoutManager(layoutManager);
list = sessionManager.getItems(getContext());
RecyclerDetails.addOnItemTouchListener(new RecyclerItemClickListener(getContext(), new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
}));
if(list != null){
Toasty.info(getContext(),"Swipe to go to Next", Toast.LENGTH_LONG,true).show();
adapter = new CartAdapter(getContext(),list);
RecyclerDetails.setAdapter(adapter);
}
//initswipe();
return view;
}
}
In your session manager something's not right with the savetocart() method.
The first time it called, getItems() will return null as expected, therefore the if statement in the next line will resolve to true and an item will be added. But after that itemList will not be null, therefore the if statement will always resolve to false and no items are added to the list.
That method should look like this
public void savetocart(Context context, SingleItem singleitems){
List<SingleItem> itemList = getItems(context);
if (itemList == null) {
itemList = new ArrayList<>();
}
itemList.add(singleitems);
saveitems(context, itemList);
}

Retrofit and RecyclerView not displaying items on startup

In my app is Retrofit 1.9 and RecyclerView. On startup HTTP request is sending and I receive data, but not displaying. After SwipeRefresh data are downloaded again, but before that Recycler is displaying previous data.
Fragment:
package com.example.bolek.testy.Fragments;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.support.v7.widget.DefaultItemAnimator;
import android.widget.Toast;
import com.example.bolek.testy.Adapters.ChaptersAdapter;
import com.example.bolek.testy.Interfaces.WebService;
import com.example.bolek.testy.Pojo.Chapter;
import com.example.bolek.testy.R;
import retrofit.Callback;
import retrofit.RestAdapter;
import retrofit.RetrofitError;
import retrofit.client.Response;
import java.util.ArrayList;
import java.util.List;
public class RetrofitFragment extends Fragment {
private List<Chapter> chapterList = new ArrayList<>();
private RecyclerView recyclerView;
private ChaptersAdapter mAdapter;
RestAdapter retrofit;
WebService webService;
SwipeRefreshLayout refreshLayout;
public RetrofitFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_retrofit, container, false);
}
#Override
public void onViewCreated(View v, Bundle savedInstanceState) {
recyclerView = (RecyclerView) v.findViewById(R.id.recycler_view);
refreshLayout = (SwipeRefreshLayout) v.findViewById(R.id.swipeRefreshLayout);
RecyclerView.LayoutManager mLayoutManager;
int screenSize = getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK;
//sprawdzanie rozmiaru ekranu
switch (screenSize) {
case Configuration.SCREENLAYOUT_SIZE_SMALL:
mLayoutManager = new GridLayoutManager(getActivity().getApplicationContext(), 1);
break;
case Configuration.SCREENLAYOUT_SIZE_LARGE:
case Configuration.SCREENLAYOUT_SIZE_XLARGE:
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
mLayoutManager = new GridLayoutManager(getActivity().getApplicationContext(), 5);
} else {
mLayoutManager = new GridLayoutManager(getActivity().getApplicationContext(), 4);
}
break;
default:
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
mLayoutManager = new GridLayoutManager(getActivity().getApplicationContext(), 4);
} else {
mLayoutManager = new GridLayoutManager(getActivity().getApplicationContext(), 2);
}
}
mAdapter = new ChaptersAdapter(chapterList, getContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
Log.i("aaaaaaaaaaaa", "startup");
prepareData(true);
refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
Log.i("aaaaaaaaaaaa", "onRefresh called from SwipeRefreshLayout");
prepareData(true);
}
});
}
private void prepareData(final boolean refresh) {
retrofit = new RestAdapter.Builder()
.setEndpoint("http://bolex.cba.pl/")
.setLogLevel(RestAdapter.LogLevel.FULL)
.build();
webService = retrofit.create(WebService.class);
try {
webService.getData(new Callback<Chapter[]>() {
#Override
public void success(Chapter[] data, Response response) {
if (refresh) {
chapterList.clear();
}
for (Chapter item : data) {
chapterList.add(item);
}
refreshLayout.setRefreshing(false);
}
#Override
public void failure(RetrofitError error) {
Toast.makeText(getActivity().getApplicationContext(), error.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
Log.d("Rest", error.getLocalizedMessage());
}
});
} catch (Exception e) {
Log.d("Rest", e.toString());
}
mAdapter.notifyDataSetChanged();
}
}
Adapter:
package com.example.bolek.testy.Adapters;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import java.util.List;
import com.example.bolek.testy.Pojo.Chapter;
import com.example.bolek.testy.R;
public class ChaptersAdapter extends RecyclerView.Adapter<ChaptersAdapter.MyViewHolder> {
private List<Chapter> chapterList;
private Context mContext;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView date, number, title;
private ImageView cover;
public MyViewHolder(View view) {
super(view);
date = (TextView) view.findViewById(R.id.date);
cover = (ImageView) view.findViewById(R.id.cover);
number = (TextView) view.findViewById(R.id.number);
title = (TextView) view.findViewById(R.id.title);
}
}
public ChaptersAdapter(List<Chapter> chapterList, Context mContext) {
this.chapterList = chapterList;
this.mContext = mContext;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.chapter_list_item, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Chapter chapter = chapterList.get(position);
holder.title.setText(chapter.getTitle());
if(chapter.getDate() == null){
Log.d("aaaaaaaaaaaaaaaaaaaaa","null");
}
Glide.with(mContext).load("https://novelki.pl/uploads/"+chapter.getImage())
.thumbnail(0.5f)
.error(R.drawable.no_foto)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(holder.cover);
holder.date.setText(chapter.getDate());
holder.number.setText("Tom " + chapter.getTomNumber() + " chapter " + chapter.getChapterNumber());
}
#Override
public int getItemCount() {
return chapterList.size();
}
}
Any idea?
P.S.
Sorry for my bad english.
I think you might not be updating you adapter when the data comes:
private void prepareData(final boolean refresh) {
#Override
public void success(Chapter[] data, Response response) {
retrofit = new RestAdapter.Builder()
.setEndpoint("http://bolex.cba.pl/")
.setLogLevel(RestAdapter.LogLevel.FULL)
.build();
webService = retrofit.create(WebService.class);
try {
webService.getData(new Callback<Chapter[]>() {
#Override
public void success(Chapter[] data, Response response) {
if (refresh) {
chapterList.clear();
}
for (Chapter item : data) {
chapterList.add(item);
}
// I JUST ADDED THIS LINE BELOW
mAdapter.notifyDataSetChanged();
refreshLayout.setRefreshing(false);
}
...
}

RecyclerView giving errors

Hi i am new to android project so i am trying to use recycler view. but it is not working. i keep getting errors # this line " RecyclerAdapter adapter = new RecyclerAdapter(this, getData());" it says RecyclerAdapter (android.content.context, List) in RecyclerAdapter cannot be applied to my package class please help
statement.java
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import java.util.ArrayList;
import java.util.List;
import nnnnn.R;
import nnnnnn.RecyclerAdapter;
import nnnnnnnnnnnnn.Landscape;
public class Statements extends Fragment {
Toolbar toolbar;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.statements,container,false);
toolbar = (Toolbar) v.findViewById(R.id.toolbar);
toolbar.setTitle("Statements");
toolbar.inflateMenu(R.menu.menu_main);
setUpRecyclerView();
return v;}
private void setUpRecyclerView() {
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
RecyclerAdapter adapter = new RecyclerAdapter(this.getActivity(),Landscape.getData());
recyclerView.setAdapter(adapter);
final LinearLayoutManager mLinearLayoutManagerVertical = new LinearLayoutManager(this.getActivity()); // (Context context, int spanCount)
mLinearLayoutManagerVertical.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(mLinearLayoutManagerVertical);
recyclerView.setItemAnimator(new DefaultItemAnimator()); // Even if we dont use it then also our items shows default animation. #Check Docs
}
}
RecyclerAdapter code is below
RecyclerAdapter
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
import xx.xx.xx.xx.xx.R;
import xx.xx.xx.xx.model.Landscape;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder> {
private static final String TAG = RecyclerAdapter.class.getSimpleName();
private List<Landscape> mDataList;
private LayoutInflater inflater;
public RecyclerAdapter(Context context, List<Landscape> data) {
this.mDataList = data;
this.inflater = LayoutInflater.from(context);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.i(TAG, "onCreateViewHolder");
View view = inflater.inflate(R.layout.statementlist, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Log.i(TAG, "onBindViewHolder" + position);
Landscape current = mDataList.get(position);
holder.setData(current, position);
holder.setListeners();
}
#Override
public int getItemCount() {
return mDataList.size();
}
public void removeItem(int position) {
mDataList.remove(position);
notifyItemRemoved(position);
// notifyItemRangeChanged(position, mDataList.size());
// notifyDataSetChanged();
}
public void addItem(int position, Landscape landscape) {
mDataList.add(position, landscape);
notifyItemInserted(position);
// notifyItemRangeChanged(position, mDataList.size());
// notifyDataSetChanged();
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView title;
ImageView imgThumb, imgDelete, imgAdd;
int position;
Landscape current;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.tvTitle);
imgThumb = (ImageView) itemView.findViewById(R.id.img_row);
imgDelete = (ImageView) itemView.findViewById(R.id.img_row_delete);
imgAdd = (ImageView) itemView.findViewById(R.id.img_row_add);
}
public void setData(Landscape current, int position) {
this.title.setText(current.getTitle());
imgThumb.setImageResource(current.getImageID());
this.position = position;
this.current = current;
}
public void setListeners() {
imgDelete.setOnClickListener(MyViewHolder.this);
imgAdd.setOnClickListener(MyViewHolder.this);
imgThumb.setOnClickListener(MyViewHolder.this);
}
#Override
public void onClick(View v) {
// Log.i("onClick before operation", position + " " + mDataList.size());
switch (v.getId()) {
case R.id.img_row_delete:
removeItem(position);
break;
case R.id.img_row_add:
addItem(position, current);
break;
}
// Log.i("onClick after operation", mDataList.size() + " \n\n" + mDataList.toString());
}
}
}
You're passing in "this" for the first argument to RecyclerAdapter. "this" being a Fragment class. The Fragment class does not extend from Context, so it cannot be used as such.
Try "this.getActivity()". This may result in null, so ideally put this within the Fragment subclass's "onActivityCreated" method (instead of the "onCreateView" method)
You need to override OnActivitycreated in order to call getActivity. Call setUpRecyclerView in OnActivitycreated and add getActivity. before findViewById and it will work

Categories

Resources