i am trying to update recyclerview with images from a API using ASYNC task but its not working properly . The problem is with the notifyDataSetChanged() method in the onPostExecute() of the ASYNC task. i have checked the json response and the result of the onPostExecute() the value are correct but the notifydatasetchanged() is not updating the adapter with the new data.
MainActivity :
public class MainActivity extends AppCompatActivity {
public static final String LOG_TAG = MainActivity.class.getName();
public MovieUtils utils = new MovieUtils();
private RecyclerView mRecyclerView;
private MovieAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
public ArrayList<String> movieData=new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
//Using a grid layout manager to display the movies in a grid view.
mLayoutManager = new GridLayoutManager(getApplicationContext(), 2);
mRecyclerView.setLayoutManager(mLayoutManager);
//using the jsonParser to parse the String response and create a new data set.
// passing the data to the Adapter.
mAdapter = new MovieAdapter(movieData, getApplicationContext());
mRecyclerView.setAdapter(mAdapter);
DownloadMovieDetail downloadMovieDetail= new DownloadMovieDetail();
downloadMovieDetail.execute();
}
private class DownloadMovieDetail extends AsyncTask<String, Void, ArrayList<String>> {
#Override
protected ArrayList<String> doInBackground(String... params) {
ArrayList<String> movieDb = new ArrayList<String>();
try {
movieDb = utils.downloadMovie(responseString);
} catch (IOException e) {
e.printStackTrace();
}
return movieDb;
}
#Override
protected void onPostExecute(ArrayList<String> strings) {
movieData.addAll(strings);
Log.v(LOG_TAG,"the movie data"+movieData.toString());
mAdapter.notifyDataSetChanged();
}
}
}
Movie Adapter:
public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.ViewHolder> {
public static final String LOG_TAG = MovieAdapter.class.getName();
public ArrayList<String> dummyData;
public Context context;
public static class ViewHolder extends RecyclerView.ViewHolder {
public ImageView MovieImageView;
public ViewHolder(View itemView) {
super(itemView);
MovieImageView=(ImageView) itemView.findViewById(R.id.movie_image);
}
}
//Constructor for the adapter.
public MovieAdapter(ArrayList<String> data, Context c){
this.context=c;
dummyData=data;
}
#Override
public MovieAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.movie_view, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(MovieAdapter.ViewHolder holder, int position) {
Picasso.with(context).load(dummyData.toString()).into(holder.MovieImageView);
}
#Override
public int getItemCount()
{
return dummyData.size();
}
}
Define a setter for dummyData ArrayList in your adapter like this
public void setDummyData(ArrayList<String> data){
this.dummyData = data;
notifyDataSetChanged();
}
and then onPostExecute() replace
mAdapter.notifyDataSetChanged();
with
mAdapter.setDummyData(movieData);
You did't change the data on the adapter class. Create a setter for the ArrayList and then call notifyDataSetChanged()
public void setList(ArrayList<String> dummyData){
this.dummyData = dummyData;
notifyDataSetChanged();
}
And on onPostExecute just call
adapter.setList(string);
Related
Conditions:
I have an Activity and I'm creating PagerAdapter extends FragmentPagerAdapter with one Fragment class. TabLayout includes 10 tabs. I have TabLayout.addOnTabSelectedListener and there in onTabSelected() I am updating some custom variable in app's SharedPreferences which depends on current tab name and tab index. Tab's names are not static - there are loading from server too.
My task:
With this value I should make a retrofit2 Call to my server and load values in adapter with recyclerview for my Fragment.
My problem:
I am loading the same data for the different tabs, which should contatin different data! I am understand that this happens because in all cases I have the same SharedPreferences variable's value so I am making retrofit Call with same conditions.
setOffscreenPageLimit() can't be setted to 0 - default is 1 according documentation:
https://developer.android.com/reference/kotlin/androidx/viewpager/widget/ViewPager#setoffscreenpagelimit;
setUserVisibleHint() on SO I've found this like some variant for solving my problem, but it can't be overrided because is deprecated now.
Solution:
I think I should save previous and next tab name in some way and then I can make different parallel retrofit Calls with different conditions. When tab selected I can get current, previous and next tab name. But how, where and when I should make two more retrofit calls?
UPD 08.02.2022: Still thinking about this problem.
Code:
SomeActivity.java
public class SomeActivity extends BaseActivity {
private String TAG="SomeActivity";
private Context context;
private TabLayout tabs;
private ViewPager viewpager;
private ProgressBar PBLoading;
private PagerAdapter_SomePAdapter adapter;
List<String> names = new ArrayList<>();
private String[] tabTitles;
public String previousTabName;
public String nextTabName;
public int counterForPreviousTabName;
public int counterForNextTabName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout);
context = getApplicationContext();
String categories = AppPreferences.getCategories(context);
tabTitles = categories.split(";");
tabs = findViewById(R.id.tabs);
viewpager = findViewById(R.id.viewpager);
PBLoading = findViewById(R.id.PBLoading);
tabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
Log.d(TAG, "onTabSelected");
AppPreferences.setCurrentValueForRetrofit(getApplicationContext(), tab.getPosition());
counterForPreviousTabName = tmpTab.getPosition() - 1;
counterForNextTabName = tmpTab.getPosition() + 1;
//here I can get tab names.
}
});
adapter = new PagerAdapter_SomePAdapter(getSupportFragmentManager(), SomeActivity.this);
viewpager.setAdapter(adapter);
adapter.updateTitleData(tabTitles);
tabs.setupWithViewPager(viewpager);
adapter.notifyDataSetChanged();
}
}
PagerAdapter_SomePAdapter.java:
public class PagerAdapter_SomePAdapter extends FragmentPagerAdapter {
int PAGE_COUNT = 2;
private String[] tabTitles = new String[] { "", ""};
private Context mContext;
Fragment_fragment fragment_fragment;
String TAG = "PagerAdapter_SomePAdapter";
public PagerAdapter_SomePAdapter(FragmentManager fm, Context context) {
super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
mContext = context;
fragment_fragment = new Fragment_fragment();
}
#Override public int getCount() {
return PAGE_COUNT;
}
#Override public Fragment getItem(int position) {
return fragment_fragment.newInstance(position + 1, tabTitles[position]);
}
#Override public CharSequence getPageTitle(int position) {
return tabTitles[position];
}
public void updateTitleData(String[] tabTitlesNew) {
tabTitles = tabTitlesNew;
PAGE_COUNT = tabTitlesNew.length;
notifyDataSetChanged();
}
}
Fragment_fragment.java:
public class Fragment_fragment extends Fragment {
private String TAG = "Fragment_fragment";
private static final String ARG_PAGE = "ARG_PAGE";
private int mPage;
private View rootView;
private RecyclerView RV;
private Adapter_Items adapter;
public static Fragment_fragment newInstance(int page, String tabName) {
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
Fragment_fragment fragment = new Fragment_fragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mPage = getArguments().getInt(ARG_PAGE);
}
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
mContext=context;
}
#SuppressLint("ClickableViewAccessibility")
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.content_list, container, false);
RV = rootView.findViewById(R.id.recycler_view);
new loadDataAS().execute();
return rootView;
}
private void loadData(){
//retrofit call code;
}
class loadDataAS extends AsyncTask<Void, Void, Void> {
final ProgressDialog progress = new ProgressDialog(mContext);
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
loadData();
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
adapter = new Adapter_Items(arguments, arguments2, arguments3);
RV.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
}
Adapter_Items:
public class Adapter_Items extends RecyclerView.Adapter<Adapter_Items.ViewHolder>{
private LayoutInflater mInflater;
private Context mContext;
private static String TAG = "Adapter_Items";
public Adapter_Items(List<Integer>arguments, List<String>arguments2, List<String>arguments3){
//initializing arguments
}
// inflates the row layout from xml when needed
#NotNull
#Override
public ViewHolder onCreateViewHolder(#NotNull ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recycle_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
//setting view's information
}
#Override
public int getItemCount() {
return arguments.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
}
}
}
First thing,
fragment should contain different data
Saving tab name after tab selected will not work. You should remove this
AppPreferences.setCurrentValueForRetrofit(getApplicationContext(),
tab.getPosition());
You should call retrofit code inside the fragment with the tabName (Not from sharedPref) to get data for that tab.
For this, make the following changes,
You are already passing the tabName to fragment instance
newInstance(int page, String tabName)
use that tabName and pass to your AsyncTask -> loadData() as
loadData(tabName);
Then you can use that in your retrofit call and get the data.
Note:
setOffscreenPageLimit()
This method will load fragments just before they are completely visible. It would be useful and a great user experience to display data directly rather than fetching only when user selects the tab.
Here is what I was trying to do. addNewQRCard() is onclick event fired by a button to add new images to viewpager. I have to always set the adapter to new items. But why in my case onStart() doesn't do that job. Please give me the best practice that I should use to add and delete views dynamically from viewPager2.
public class AddPage extends AppCompatActivity {
private ViewPager2 viewPager2;
private ArrayList<ModelItem> items;
private AdapterSlider adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_qrcode);
viewPager2 = findViewById(R.id.viewPagerImageSlider);
items = new ArrayList<>();
items.add(new ModelItem(R.drawable.image1));
adapter = new AdapterSlider(items,viewPager2);
viewPager2.setAdapter(adapter);
viewPager2.setClipToPadding(false);
viewPager2.setClipChildren(false);
viewPager2.setOffscreenPageLimit(3);
viewPager2.getChildAt(0).setOverScrollMode(RecyclerView.OVER_SCROLL_NEVER);
CompositePageTransformer compositePageTransformer = new CompositePageTransformer();
compositePageTransformer.addTransformer(new MarginPageTransformer(40));
compositePageTransformer.addTransformer(new ViewPager2.PageTransformer() {
#Override
public void transformPage(#NonNull View page, float position) {
float r = 1 - Math.abs(position);
page.setScaleY(0.85f + r * 0.15f);
}
});
viewPager2.setPageTransformer(compositePageTransformer);
}
#Override
protected void onStart() {
super.onStart();
adapter = new AdapterQRSlider(sliderItems,viewPager2);
viewPager2.setAdapter(adapter);
}
public void addNewQRCard(View view) { //this is the button which i used to add new childs
items.add(new ModelSlider(R.drawable.image2));
adapter = new AdapterSlider(items,viewPager2);
viewPager2.setAdapter(adapter);
}
}
Adapter class
public class AdapterSliderextends RecyclerView.Adapter<AdapterSlider.ViewHolder>{
private ArrayList<ModelSlider> items;
private ViewPager2 viewPager2;
public AdapterSlider(ArrayList<ModelSlider> items, ViewPager2 viewPager2) {
this.items= items;
this.viewPager2 = viewPager2;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new ViewHolder(
LayoutInflater.from(parent.getContext()).inflate(
R.layout.slide_item_container,
parent,
false
)
);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.setImage(items.get(position));
}
#Override
public int getItemCount() {
return items.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
private ImageView imageView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageSlide);
}
void setImage(ModelSlider items){
imageView.setImageResource(sliderItem.getImage());
}
}
}
Model Class
public class ModelSlider {
private int image;
public ModelSlider(int image){
this.image = image;
}
public int getImage() {
return image;
}
}
You can notify adapter when you adding new items just like the way you do it with RecyclerView. Something like this
public void addNewQRCard(View view) {
items.add(new ModelSlider(R.drawable.image2));
// instead of of resetting adapter to ViewPager,
// just notify its adapter of item inserted
adapter.notifyItemInserted(items.size - 1)
}
I have api call request with parameters: (page,pageSize:the maximum number of items desired(default 25,Maximum 100.From reddit api documentation)),and i want to use pagination in RecyclerView.My data is loading successfully but the problem how do i request to server for the next page.How i can perform pagination with method addOnScrollListener
WebService Class
public interface RedditWebService {
#GET("top.json")
Observable<Response> getTopPublication(#Query("count")int count,
#Query("limit")int pageSize);
}
Adapter Class
public class RedditAdapter extends RecyclerView.Adapter<RedditAdapter.RedditViewHolder> {
private List<Child> childList;
private Context context;
public RedditAdapter(Context context, List<Response.Data.Child> childList) {
this.childList = childList;
this.context = context;
}
#NonNull
#Override
public RedditViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.items_layout, parent, false);
return new RedditViewHolder(view);
}
#SuppressLint("DefaultLocale")
#Override
public void onBindViewHolder(#NonNull RedditViewHolder holder, int position) {
final Child child = childList.get(position);
holder.txtAuthor.setText(child.getmData().getmAuthor());
String timeAgo = TimeAgo.getTimeAgo(child.getmData().getmCreated());
Log.d("Time", "" + timeAgo);
holder.txtDate.setText(timeAgo);
holder.txtComment.setText(String.format("Comments: %d", child.getmData().getmNumComments()));
Picasso.get().load(child.getmData().getmThumbnail()).placeholder(R.drawable.placeholder).
transform(ImageTransformation.getTransformation(holder.imageView)).into(holder.imageView);
if (!child.getmData().getmThumbnail().equals("")) {
holder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context.getApplicationContext(), SecondActivity.class);
intent.putExtra("extraImage", child.getmData().getmThumbnail());
context.startActivity(intent);
}
});
}
}
#Override
public int getItemCount() {
return (childList == null) ? 0 : childList.size();
}
public class RedditViewHolder extends RecyclerView.ViewHolder {
private ImageView imageView;
private TextView txtDate, txtAuthor, txtComment;
public RedditViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.image_view);
txtDate = itemView.findViewById(R.id.txt_date);
txtAuthor = itemView.findViewById(R.id.txt_author);
txtComment = itemView.findViewById(R.id.txt_comments_num);
}
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private LinearLayoutManager layoutManager;
private ProgressBar progressBar;
private RedditAdapter adapter;
private List<Child> redditList = new ArrayList<>();
private CompositeDisposable disposable = new CompositeDisposable();
private int page = 0;
private int pageSize = 50;
#Inject
RedditWebService webService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((BaseApplication) getApplication()).getComponent().inject(this);
setContentView(R.layout.activity_main);
progressBar = findViewById(R.id.progress_bar);
recyclerView = findViewById(R.id.recycler_view);
layoutManager = new LinearLayoutManager(this);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(layoutManager);
fetchData();
}
private void fetchData() {
progressBar.setVisibility(View.VISIBLE);
disposable.add(webService.getTopPublication(page,pageSize)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<Response>() {
#Override
public void accept(Response response) throws Exception {
adapter = new RedditAdapter(MainActivity.this, response.getData().getChildren());
recyclerView.setAdapter(adapter);
progressBar.setVisibility(View.GONE);
}
}, new Consumer<Throwable>() {
#Override
public void accept(Throwable throwable) throws Exception {
Toast.makeText(MainActivity.this, throwable.toString(), Toast.LENGTH_LONG).show();
}
}));
}
Thanks in advance
Use EndlessRecyclerViewScrollListener.java, it will provide very easy way to do load more call.
Maintain one global variable "page" initialize by 1, and increase it by 1 on every API call or load more call.
EndlessRecyclerViewScrollListener scrollListener = new EndlessRecyclerViewScrollListener(linearLayoutManager) {
#Override
public void onLoadMore(int page, int totalItemsCount, RecyclerView view) {
// Triggered only when new data needs to be appended to the list
// Add whatever code is needed to append new items to the bottom of the list
page++;
loadMoreCall(page);
}
};
inside loadMoreCall() you need to add your api call, and after successfull api call, you need to set data to your list and then you need to notify your adaper. thats it only.
reference: https://guides.codepath.com/android/endless-scrolling-with-adapterviews-and-recyclerview
here how to call, api using retrofit:
https://demonuts.com/android-recyclerview-retrofit/
Consider using the new paging library. Here's a sample and the documentation. It performs better and you don't have to manually keep track where you are in the scrolling. By following the sample I found it fairly easy to implement this, although it is a lot of boilerplate code.
I am trying to set the data for recycler view to display from an AsyncTask. I am calling the method setdataEntries from the postExecute of inner class AsyncTask. But the android studio is showing me error could not find the method.
Adapter class
public class EntryAdapter extends RecyclerView.Adapter<EntryAdapter.ViewHolder> {
List<UserTuple> entries;
final private itemClickListener mOnClickListener;
public interface itemClickListener{
void onItemClick(UserTuple utuple);
}
public EntryAdapter(itemClickListener clickhandler) {
mOnClickListener = clickhandler;
}
public void setdataEntries(List<UserTuple> Data) {
entries = Data;
notifyDataSetChanged();
}
#Override
public EntryAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.singleusertuple,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(EntryAdapter.ViewHolder holder, int position) {
holder.Username.setText(entries.get(position).getUsername());
holder.Password.setText(entries.get(position).getPassword());
}
#Override
public int getItemCount() {
return entries.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView Username;
private TextView Password;
private CardView card;
public ViewHolder(View itemView) {
super(itemView);
Username = itemView.findViewById(R.id.susername);
Password=itemView.findViewById(R.id.pass);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int adapterPosition = getAdapterPosition();
UserTuple ut=new UserTuple(entries.get(adapterPosition).getUsername(),entries.get(adapterPosition).getPassword());
mOnClickListener.onItemClick(ut);
}
}
}
Calling Activity
public class Usertuple extends AppCompatActivity implements EntryAdapter.itemClickListener {
private RecyclerView recyclerView ;
private RecyclerView.Adapter adapater;
private SnapHelper snapHelper;
private List<UserTuple> entries;
private ProgressBar mLoadingIndicator;
private Bundle extras;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_logins);
extras = getIntent().getExtras();
//String site= extras.getString("sitename");
mLoadingIndicator = (ProgressBar) findViewById(R.id.pb_loading_indicator);
Log.i("Logins","Size of returned list "+entries.size());
recyclerView = findViewById(R.id.recycleview);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
adapater = new EntryAdapter(this);
recyclerView.setAdapter(adapater);
snapHelper= new LinearSnapHelper();
snapHelper.attachToRecyclerView(recyclerView);
dataView();
}
public void dataView() {
String site= extras.getString("sitename");
recyclerView.setVisibility(View.VISIBLE);
new FetchDataTask().execute(site);
}
#Override
public void onItemClick(UserTuple utuple) {
}
private String key(){
SharedPreferences sharedPref = getSharedPreferences(
"User", this.MODE_PRIVATE);
final String passphrase = sharedPref.getString("userid", "none");
return passphrase;
}
public void showerror(){
recyclerView.setVisibility(View.GONE);
Toast.makeText(this,"Error in retrieving",Toast.LENGTH_SHORT).show();
}
public setdata(List<UserTuple> data){
adapater.setdataEntries(data);
}
public class FetchDataTask extends AsyncTask<String, Void, List<UserTuple>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mLoadingIndicator.setVisibility(View.VISIBLE);
}
#Override
protected List<UserTuple> doInBackground(String... params) {
/* If there's no zip code, there's nothing to look up. */
if (params.length == 0) {
return null;
}
String site = params[0];
try {
AppDatabase db = Room.databaseBuilder(getApplicationContext(),AppDatabase.class, "production")
.build();
entries =db.entryDao().getSpecific(site);
for(UserTuple ut : entries){
Log.i("password",ut.getPassword());
String st = new Decryption().decrypt(ut.getPassword(),key());
Log.i("After decryption",st);
ut.setPassword(st);
}
return entries;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(List<UserTuple> Data) {
mLoadingIndicator.setVisibility(View.INVISIBLE);
if (Data != null) {
adapater.setdataEntries(Data);
} else {
showerror();
}
}
}
}
I want the database calls to be a background task. I don't want the activity to freeze waiting for database calls. Any ideas? Thanks
Declare adapter like
private EntryAdapter adapter;
instead of
private RecyclerView.Adapter adapater;
because RecyclerView.Adapter class does not have any method named setdataEntries but only EntryAdapter class has this method so only the object of type EntryAdapter can call setdataEntries method.
Or you can use down-casting as
((EntryAdapter)adapater).setdataEntries(data);
I'm writing a simple app which requires me to remember all checkbox states which are dynamically generated.
I'm trying to use SharedPreferences to save the states of these, I'm using an recyclerview, so I've defined my sharedpreferences and all in the mainactivity which extends Activity.
All good and well, now I'm trying to use this in my Adapter class by trying referencing MainActivity.data, without luck.
MainActivity relevant code:
public class MainActivity extends Activity {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
public static String FILENAME = "AnimeConfig";
public SharedPreferences data = getSharedPreferences(FILENAME, 0);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new GetAnime().execute();
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
}
private class GetAnime extends AsyncTask<Void, Void, Void> {
private String animeUrl = "http://www.animeseason.com/anime-list";
public List<String> animes = new ArrayList<String>();
#Override
protected Void doInBackground(Void... params) {
try {
Document document = Jsoup.connect(animeUrl).get();
Elements elements = document.select("div.series_alpha span");
for (Element element : elements) {
animes.add(element.previousElementSibling().text());
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
mAdapter = new MyAdapter(animes);
mRecyclerView.setAdapter(mAdapter);
}
}
MyAdapter relevant code:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<String> mDataset;
public static class ViewHolder extends RecyclerView.ViewHolder {
public CheckBox mCheckbox;
public ViewHolder(CheckBox v) {
super(v);
mCheckbox = v;
}
}
public MyAdapter(List<String> animes) {
mDataset = animes;
}
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
CheckBox v = (CheckBox) LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item, viewGroup, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.mCheckbox.setText(mDataset.get(position));
holder.mCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
String animeName = buttonView.getText().toString();
SharedPreferences.Editor editor = MainActivity.data.edit();
}
}
});
}
#Override
public int getItemCount() {
return mDataset.size();
}
}
I don't understand why I can't use MainActivity.data.
you should declare SharedPreferences data as static so you can access it from other classes .
but i prefer to use helper class to do all this work for me
something like this :
public class GeneralHelper {
public static SharedPreferences getSharedPrefrence(Context contextversion) {
//do the code for getting SharedPreferences
}
}