Error with InitLoader again - java

I want to create a loader for my list view but got
The method initLoader(int, Bundle, LoaderManager.LoaderCallbacks) in the type LoaderManager is not applicable for the arguments (int, null, context)
know this error is very common but tried to import different library still error. Really appreciate if someone can point out why. Thanks in advance!
my code:
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.app.Fragment;
import android.content.AsyncTaskLoader;
import android.content.Loader;
import android.app.LoaderManager;
import android.app.LoaderManager.LoaderCallbacks;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.view.View.OnClickListener;
import android.app.Activity;
public class WhiteNote extends Fragment implements LoaderManager.LoaderCallbacks<ArrayList<NoteItems>> {
private NoteDatabase note_database;
private int i=0;
public Context context;
public NoteListAdapter noteListAdapter;
public ListView note_listview_container;
public SQLiteDatabase note_sqldb;
public Cursor c;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.white_note, container, false);
context=getActivity();
note_database = new NoteDatabase(context);
final EditText text_ed_1;
final EditText text_ed_2;
Button button_addNote;
Button button_listallNote;
Button button_delallNote;
text_ed_1 = (EditText)rootView.findViewById(R.id.textedit1);
text_ed_2 = (EditText)rootView.findViewById(R.id.textedit2);
button_addNote = (Button)rootView.findViewById(R.id.button1);
button_listallNote = (Button)rootView.findViewById(R.id.button2);
button_delallNote = (Button)rootView.findViewById(R.id.button3);
note_listview_container=(ListView)rootView.findViewById(R.id.note_listview);
//showNoteList();
button_addNote.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
note_database.open();
note_database.createData(text_ed_1.getText().toString(),text_ed_2.getText().toString());
//i++;
note_database.close();
}
});
button_listallNote.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
note_database.open();
//String ds = note_database.getData();
note_database.get_NoteListAdapter();
note_listview_container.setAdapter(note_database.noteListAdapter);
getLoaderManager().initLoader(0, null, context);
note_database.close();
//note_list.setText(ds);
}
});
button_delallNote.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
note_database.open();
note_database.deleteAllNote();
note_database.close();
}
});
return rootView;
}
#Override
public Loader<ArrayList<NoteItems>> onCreateLoader(int id, Bundle args) {
return new NoteItemsLoader(context, note_database);
}
#Override
public void onLoadFinished(Loader<ArrayList<NoteItems>> loader,
ArrayList<NoteItems> data) {
note_listview_container.setAdapter(new NoteListAdapter(context,data));
}
#Override
public void onLoaderReset(Loader<ArrayList<NoteItems>> loader) {
note_listview_container.setAdapter(null);
}
}
// THE LOADER
class NoteItemsLoader extends AsyncTaskLoader<ArrayList<NoteItems>> {
private ArrayList<NoteItems> loader_note_items;
private NoteDatabase loader_db;
public NoteItemsLoader(Context context, NoteDatabase db) {
super(context);
this.loader_db = db;
}
#Override
protected void onStartLoading() {
if (loader_note_items != null) {
deliverResult(loader_note_items); // Use the cache
}
else
forceLoad();
}
#Override
protected void onStopLoading() {
cancelLoad();
}
#Override
public ArrayList<NoteItems> loadInBackground() {
loader_db.open(); // Query the database
ArrayList<NoteItems> note_items = loader_db.getNote_items();
loader_db.close();
return loader_note_items;
}
#Override
public void deliverResult(ArrayList<NoteItems> data) {
loader_note_items = data; // Caching
super.deliverResult(data);
}
#Override
protected void onReset() {
super.onReset();
onStopLoading();
loader_note_items = null;
}
#Override
public void onCanceled(ArrayList<NoteItems> data) {
super.onCanceled(data);
loader_note_items = null;
}
protected void onReleaseResources(ArrayList<NoteItems> data) {}
}

Related

Listener from DialogFragment to Fragment

I'm a beginner in Java and I'm trying to create a listener in my DialogFragment to notice my fragment that some book was removed. When the user removes a book, I want to call the removeBook method in BookFragment and update the recyclerview.
Here is my BookDialogFragment.java:
package com.compose.dietapp.ui.books;
import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.DialogFragment;
import java.util.Objects;
public class BookDialogFragment extends DialogFragment {
private final String nameToDelete;
private final int position;
private static String MESSAGE_TO_DIALOG_FRAGMENT;
public BookDialogFragment(String nameToDelete, int position) {
this.nameToDelete = nameToDelete;
this.position = position;
}
public static BookDialogFragment newInstance(String title, String nameToDelete, int position) {
BookDialogFragment frag = new BookDialogFragment(nameToDelete, position);
if (Objects.equals(nameToDelete, "none")) {
MESSAGE_TO_DIALOG_FRAGMENT = "Book removed!";
} else {
MESSAGE_TO_DIALOG_FRAGMENT = "Are you sure you want to remove the book '"
+ nameToDelete
+ "'?";
}
Bundle args = new Bundle();
args.putString("title", title);
frag.setArguments(args);
return frag;
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
assert getArguments() != null;
String title = getArguments().getString("title");
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
alertDialogBuilder.setTitle(title);
alertDialogBuilder.setMessage(MESSAGE_TO_DIALOG_FRAGMENT);
if (Objects.equals(MESSAGE_TO_DIALOG_FRAGMENT, "Book removed!")) {
alertDialogBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (dialog != null) {
dialog.dismiss();
}
}
});
} else {
alertDialogBuilder.setPositiveButton("Remove", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// here I want to callback my fragment
BookFragment deleteBook = new BookFragment();
deleteBook.removeBook(nameToDelete, position);
Bundle result = new Bundle();
result.putBoolean("value", true);
getParentFragmentManager().setFragmentResult("removed", result);
}
});
alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (dialog != null) {
dialog.dismiss();
}
}
});
}
return alertDialogBuilder.create();
}
#Override
public void onStart() {
super.onStart();
((AlertDialog) Objects.requireNonNull(getDialog())).getButton(AlertDialog.BUTTON_NEGATIVE)
.setTextColor(Color.rgb(128, 128, 128));
}
}
And here is my BookFragment.java:
package com.compose.dietapp.ui.books;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.compose.dietapp.R;
import com.compose.dietapp.database.DatabaseAccess;
import com.compose.dietapp.databinding.FragmentBookBinding;
import java.util.ArrayList;
public class BookFragment extends Fragment{
#SuppressLint("StaticFieldLeak")
private static Activity activity;
private RecyclerView recyclerView;
private final ArrayList<Book> itensBook = new ArrayList<Book>();
private BookAdapter bookAdapter;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
activity = this.getActivity();
View v = inflater.inflate(R.layout.fragment_book, container, false);
recyclerView = (RecyclerView) v.findViewById(R.id.book_recycler);
instanciateBooks();
return v;
}
private void instanciateBooks() {
ArrayList<ArrayList<String>> bookDatabaseValues = getDatabaseData();
if (recyclerView != null && bookDatabaseValues != null) {
createItemBook(bookDatabaseValues);
createRecyclerViewBook();
}
}
public void removeBook(String nameToDelete, int position) {
getChildFragmentManager().setFragmentResultListener("removed",
this, new FragmentResultListener() {
#Override
public void onFragmentResult(#NonNull String requestKey, #NonNull Bundle bundle) {
String result = bundle.getString("value");
Log.i("result", result);
}
});
}
private void createRecyclerViewBook() {
recyclerView.setHasFixedSize(true);
bookAdapter = new BookAdapter(activity, itensBook);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(activity,
LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(bookAdapter);
}
private void createItemBook(ArrayList<ArrayList<String>> bookDatabaseValues) {
for (int i = 0; i < bookDatabaseValues.size(); i++) {
itensBook.add(new Book(
String.valueOf(bookDatabaseValues.get(i).get(0)),
String.valueOf(bookDatabaseValues.get(i).get(1)),
String.valueOf(bookDatabaseValues.get(i).get(2)),
String.valueOf(bookDatabaseValues.get(i).get(3)),
String.valueOf(bookDatabaseValues.get(i).get(4))
));
}
}
public static ArrayList<ArrayList<String>> getDatabaseData() {
if (activity != null) {
return getArrayListsFromDatabase();
}
return null;
}
private static ArrayList<ArrayList<String>> getArrayListsFromDatabase() {
DatabaseAccess databaseAccess = openDatabase();
ArrayList<ArrayList<String>> books = databaseAccess.getBook();
closeDatabase(databaseAccess);
return books;
}
private static void closeDatabase(DatabaseAccess databaseAccess) {
databaseAccess.close();
}
#NonNull
private static DatabaseAccess openDatabase() {
DatabaseAccess databaseAccess = DatabaseAccess.getInstance(activity);
databaseAccess.open();
return databaseAccess;
}
}
Here is my BookAdapter.java:
package com.compose.dietapp.ui.books;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.RecyclerView;
import com.compose.dietapp.R;
import java.io.InputStream;
import java.util.ArrayList;
public class BookAdapter extends RecyclerView.Adapter<BookViewHolder> {
public static FragmentManager supportFragment;
private final Context context;
private final ArrayList<Book> itens;
public BookAdapter(Context context, ArrayList<Book> itens) {
this.context = context;
this.itens = itens;
}
#NonNull
#Override
public BookViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.item_recycler_book, parent, false);
BookViewHolder viewHolder = new BookViewHolder(view);
supportFragment = ((AppCompatActivity)context).getSupportFragmentManager();
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull BookViewHolder bookViewHolder, int position) {
Book book = itens.get(position);
bookViewHolder.nome.setText(book.getName());
bookViewHolder.bookType.setText(book.getBookType());
imageInstanciate(bookViewHolder);
}
private void imageInstanciate(#NonNull BookViewHolder bookViewHolder) {
new DownloadImageFromInternet((ImageView) bookViewHolder.bookImage)
.execute("https://pbs.twimg.com/profile_images/630285593268752384/iD1MkFQ0.png");
}
private class DownloadImageFromInternet extends AsyncTask<String, Void, Bitmap> {
ImageView imageView;
public DownloadImageFromInternet(ImageView imageView) {
this.imageView = imageView;
}
protected Bitmap doInBackground(String... urls) {
String imageURL = urls[0];
Bitmap bimage = null;
try {
InputStream in = new java.net.URL(imageURL).openStream();
bimage = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error Message", e.getMessage());
e.printStackTrace();
}
return bimage;
}
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
}
}
#Override
public int getItemCount() {
return itens.size();
}
}
Here is my BookViewHolder.java:
package com.compose.dietapp.ui.books;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.RecyclerView;
import com.compose.dietapp.R;
public class BookViewHolder extends RecyclerView.ViewHolder {
TextView nome;
TextView bookType;
ImageView bookImage;
public BookViewHolder(#NonNull View itemView) {
super(itemView);
nome = itemView.findViewById(R.id.nome);
bookType = itemView.findViewById(R.id.email);
bookImage = itemView.findViewById(R.id.book_image);
itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
int position = getLayoutPosition();
return true;
}
});
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String nomeDelete = nome.getText().toString();
int position = getLayoutPosition();
FragmentManager fm = BookAdapter.supportFragment;
BookDialogFragment bookDialogFragment =
BookDialogFragment.newInstance("Atenção:", nomeDelete, position);
bookDialogFragment.show(fm, "fragment_alert");
}
});
}
}
I've seen other similar solutions, but I didn't get to implement them in my code. Can anyone help me?
Going through your code, it doesn't seem like you're using Navigation Component. So let's do it this way.
Your BookDialogFragment is a child fragment to BookFragment. So basically, you should set a result in your dialog when remove button is clicked. Then set up a result listener code in you parent fragment (BookFragment), so as to get immediate result to act upon.
First part, set a result when remove is clicked
NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
...
if (Objects.equals(MESSAGE_TO_DIALOG_FRAGMENT, "Book removed!")) {
...
} else {
alertDialogBuilder.setPositiveButton("Remove", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// here I want to callback my fragment
BookFragment deleteBook = new BookFragment();
deleteBook.removeBook(nameToDelete, position);
Bundle result = new Bundle();
result.putBoolean("value", true);
getParentFragmentManager().setFragmentResult("removed", result);
}
});
alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
...
}
}
}
Then, listen for and act on the result in you BookFragment, wherever you want to, with these lines.
getChildFragmentManager().setFragmentResultListener("removed", this, new FragmentResultListener() {
#Override
public void onFragmentResult(#NonNull String requestKey, #NonNull Bundle bundle) {
// We use a Boolean here, but any type that can be put in a Bundle is supported
Boolean result = bundle.getString("value");
// Do something with the result
}
});
PS: You can use constant variables where you have "removed" and "value" for accuracy.
Hope this helps :)

android tablayout+viewPager2+recyclerView question,onTabSelected will repeated execution?

description:
the page have 4 tabs, when i first open the page. The getOrders(null, type) function will run once, type='all',
when i slip to the second,third or forth tab, The getOrders(null, type) function always will run twice, type='all' and type='paid' | 'settled' | 'invalid',
but then when i slip back, The getOrders(null, type) function always run once, and the type is correct.It is very strange,i want the getOrders always run once.
and when i do not slip but clcik the top tab,the getOrders(null, type) run normal. I need some help
the code is below
// activity
package com.sugar.sugarmall.app.pages.order;
import android.content.Context;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.sugar.sugarmall.app.R;
import com.sugar.sugarmall.app.adapter.OrderViewPagerAdapter;
import com.sugar.sugarmall.app.base.BaseActivity;
import com.sugar.sugarmall.app.config.Router;
import com.sugar.sugarmall.app.pages.mine.FragmentSetting;
import java.util.ArrayList;
import java.util.Arrays;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
#Route(path = Router.ORDER_LIST)
public class OrderActivity extends BaseActivity {
#BindView(R.id.orderPage)
ViewPager2 viewPager2;
#BindView(R.id.tabLayout)
TabLayout tabLayout;
#BindView(R.id.tv_left)
TextView backBtn;
#BindView(R.id.tv_title)
TextView topTitle;
#BindView(R.id.tv_right)
TextView topRight;
#BindView(R.id.bg_head)
LinearLayout topBox;
#BindView(R.id.topSearchCenterView)
EditText topSearchCenterView;
private final ArrayList<String> tabTitles = new ArrayList<>(Arrays.asList("全部", "已付款", "已结算", "已失效"));
private String topType = "title";
private Context context;
#Override
protected void initUI() {
setContentView(R.layout.order);
ButterKnife.bind(this);
context = getApplication();
OrderViewPagerAdapter orderViewPagerAdapter = new OrderViewPagerAdapter(this, context);
viewPager2.setAdapter(orderViewPagerAdapter);
viewPager2.setUserInputEnabled(false);
new TabLayoutMediator(tabLayout, viewPager2, new TabLayoutMediator.TabConfigurationStrategy() {
#Override
public void onConfigureTab(#NonNull TabLayout.Tab tab, int i) {
tab.setText(tabTitles.get(i));
}
}).attach();
viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
super.onPageScrolled(position, positionOffset, positionOffsetPixels);
}
#Override
public void onPageSelected(int position) {
super.onPageSelected(position);
}
#Override
public void onPageScrollStateChanged(int state) {
super.onPageScrollStateChanged(state);
}
});
backBtn.setVisibility(View.VISIBLE);
topTitle.setVisibility(View.VISIBLE);
topRight.setVisibility(View.VISIBLE);
topTitle.setText("订单明细");
topRight.setText("搜索");
}
#OnClick({R.id.tv_left, R.id.tv_right})
public void onClick(View view) {
switch (view.getId()) {
case R.id.tv_left:
onBackPressed();
break;
case R.id.tv_right:
if (topType.equals("title")) {
topTitle.setVisibility(View.GONE);
topSearchCenterView.setVisibility(View.VISIBLE);
topType = "search";
}
break;
}
if (topType.equals("title")) {
topTitle.setVisibility(View.GONE);
topSearchCenterView.setVisibility(View.VISIBLE);
topType = "search";
}
}
#Override
protected void initData() {
}
#Override
protected void initListener() {
}
}
// OrderViewPagerAdapter
package com.sugar.sugarmall.app.adapter;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import com.google.android.material.tabs.TabLayout;
import com.sugar.sugarmall.app.pages.order.FragmentOrder;
import com.sugar.sugarmall.model.bean.ItemOrderBean;
import java.util.ArrayList;
public class OrderViewPagerAdapter extends FragmentStateAdapter {
private String searchType = "";
private ArrayList<ItemOrderBean> orderList = new ArrayList<>();
private int pageNo = 1;
private Context context;
private FragmentOrder fragmentOrder = new FragmentOrder("all");
private TabLayout tabLayout;
public OrderViewPagerAdapter(#NonNull FragmentActivity fragmentActivity, Context context) {
super(fragmentActivity);
this.context = context;
}
#NonNull
#Override
public Fragment createFragment(int i) {
switch (i) {
case 0:
searchType = "all";
break;
case 1:
searchType = "paid";
break;
case 2:
searchType = "settled";
break;
default:
searchType = "invalid";
break;
}
System.out.println("-----createFragment" + searchType);
return new FragmentOrder(searchType);
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
#Override
public boolean containsItem(long itemId) {
return super.containsItem(itemId);
}
#Override
public int getItemCount() {
return 4;
}
}
// FragmentOrder
package com.sugar.sugarmall.app.pages.order;
import static com.sugar.sugarmall.config.ResStatusCode.STATUS_OK;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;
import com.google.android.material.tabs.TabLayout;
import com.sugar.sugarmall.app.R;
import com.sugar.sugarmall.app.adapter.ItemOrderAdapter;
import com.sugar.sugarmall.app.base.BaseLazyFragment;
import com.sugar.sugarmall.app.base.DefaultObserver;
import com.sugar.sugarmall.https.ApiManger;
import com.sugar.sugarmall.https.CheckResponse;
import com.sugar.sugarmall.https.response.OrderResponse;
import com.sugar.sugarmall.model.bean.ItemOrderBean;
import com.sugar.sugarmall.utils.RxTools;
import com.sugar.sugarmall.utils.T;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
public class FragmentOrder extends BaseLazyFragment {
#BindView(R.id.fragmentOrderList)
RecyclerView fragmentOrderList;
private ViewPager2 viewPager2;
private ArrayList<ItemOrderBean> orderList = new ArrayList<>();
private int pageNo = 1;
private String type = "all";
private ItemOrderAdapter itemOrderAdapter;
private TabLayout tabLayout;
private Context context;
private String[] typeArr = new String[]{"all", "paid", "settled", "invalid"};
public FragmentOrder(String type) {
this.type = type;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_order, container, false);
ButterKnife.bind(this, view);
context = getContext();
tabLayout = (TabLayout) getActivity().findViewById(R.id.tabLayout);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
fragmentOrderList.setLayoutManager(linearLayoutManager);
viewPager2 = getActivity().findViewById(R.id.orderPage);
itemOrderAdapter = new ItemOrderAdapter(orderList);
fragmentOrderList.setAdapter(itemOrderAdapter);
tabLayout.removeAllTabs();
tabLayout.clearOnTabSelectedListeners();
tabLayout.addTab(tabLayout.newTab().setText("all"));
tabLayout.addTab(tabLayout.newTab().setText("paid"));
tabLayout.addTab(tabLayout.newTab().setText("settled"));
tabLayout.addTab(tabLayout.newTab().setText("invalid"));
TabLayout.OnTabSelectedListener onTabSelectedListener = new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
System.out.println("-----pageScroll4" + tab.getPosition());
String type = typeArr[tab.getPosition()];
getOrders(null, type); // type:"all" | "paid" | "settled" | "invalid"
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
};
onTabSelectedListener.onTabSelected(tabLayout.getTabAt(tabLayout.getSelectedTabPosition()));
tabLayout.setOnTabSelectedListener(onTabSelectedListener);
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
protected void lazyload() {
}
public void getOrders(String searchKey, String type) {
RxTools.setSubscribe(ApiManger.sugarApi().getOrderList(type, pageNo, searchKey), new DefaultObserver<OrderResponse>() {
#Override
public void onNext(#io.reactivex.rxjava3.annotations.NonNull OrderResponse orderResponse) {
CheckResponse.checkResponse(orderResponse);
orderList.clear();
if (orderResponse.code != STATUS_OK) {
T.showShort(getContext(), orderResponse.msg);
}
orderList.addAll(orderResponse.data);
itemOrderAdapter.notifyDataSetChanged();
}
#Override
public void onError(#Nullable #io.reactivex.rxjava3.annotations.NonNull Throwable e) {
super.onError(e);
}
});
}
}

E/RecyclerView: No adapter attached; skipping layout / On google play billing

Hey i want to implement google billing into my app but everytime i open the activty where the button is to call my purchase the Console prints
"E/RecyclerView: No adapter attached; skipping layout"
I have a ProductAdapterclass my Information Activity where the button is located.
package com.test.smartbuyapp.Adapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.BillingFlowParams;
import com.android.billingclient.api.SkuDetails;
import com.test.smartbuyapp.InformationActivity;
import com.test.smartbuyapp.Interface.IProductClickListener;
import com.test.smartbuyapp.R;
import java.util.List;
public class MyProductAdapter extends RecyclerView.Adapter<MyProductAdapter.MyViewHolder> {
InformationActivity informationActivity;
List<SkuDetails> skuDetailsList;
BillingClient billingClient;
public MyProductAdapter(InformationActivity informationActivity, List<SkuDetails> skuDetailsList, BillingClient billingClient) {
this.informationActivity = informationActivity;
this.skuDetailsList = skuDetailsList;
this.billingClient = billingClient;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int viewType) {
View itemView = LayoutInflater.from(informationActivity.getBaseContext())
.inflate(R.layout.layout_product_item,viewGroup,false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.txt_product.setText(skuDetailsList.get(position).getTitle());
//Product click
holder.setiProductClickListener(new IProductClickListener() {
#Override
public void onProductClickListerner(View view, int position) {
//Launch Billing flow
BillingFlowParams billingFlowParams = BillingFlowParams.newBuilder()
.setSkuDetails(skuDetailsList.get(position))
.build();
billingClient.launchBillingFlow(informationActivity,billingFlowParams);
}
});
}
#Override
public int getItemCount() {
return skuDetailsList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView txt_product;
IProductClickListener iProductClickListener;
public void setiProductClickListener(IProductClickListener iProductClickListener) {
this.iProductClickListener = iProductClickListener;
}
public MyViewHolder(#NonNull View itemView) {
super(itemView);
txt_product = (TextView) itemView.findViewById(R.id.txt_product_name);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
iProductClickListener.onProductClickListerner(v, getAdapterPosition());
}
}
}
And My Informationactivity
package com.test.smartbuyapp;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.BillingClientStateListener;
import com.android.billingclient.api.BillingResult;
import com.android.billingclient.api.Purchase;
import com.android.billingclient.api.PurchasesUpdatedListener;
import com.android.billingclient.api.SkuDetails;
import com.android.billingclient.api.SkuDetailsParams;
import com.android.billingclient.api.SkuDetailsResponseListener;
import com.test.smartbuyapp.Adapter.MyProductAdapter;
import java.util.Arrays;
import java.util.List;
public class InformationActivity extends AppCompatActivity implements PurchasesUpdatedListener {
BillingClient billingClient;
Button loadProduct;
RecyclerView recyclerProduct;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_information);
setupBillingClient();
//View
loadProduct = (Button) findViewById(R.id.btn_load_product);
recyclerProduct = (RecyclerView)findViewById(R.id.recycler_product);
recyclerProduct.setLayoutManager(new LinearLayoutManager(this));
recyclerProduct.setHasFixedSize(true);
//Event
loadProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(billingClient.isReady()) {
SkuDetailsParams params = SkuDetailsParams.newBuilder()
.setSkusList(Arrays.asList("adfree"))
.setType(BillingClient.SkuType.INAPP)
.build();
billingClient.querySkuDetailsAsync(params, new SkuDetailsResponseListener() {
#Override
public void onSkuDetailsResponse(BillingResult billingResult, List<SkuDetails> list) {
if(billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK){
loadProductToRecyclerView(list);
}else{
Toast.makeText(InformationActivity.this,"Cannot query product",Toast.LENGTH_SHORT);
}
}
});
}else {
Toast.makeText(InformationActivity.this,"Billing client not Ready",Toast.LENGTH_SHORT);
}
}
});
//////////// Toolbar //////////////////////////////////////////////////////////////
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("Information");
}
private void loadProductToRecyclerView(List<SkuDetails> list) {
MyProductAdapter adapter= new MyProductAdapter(this,list,billingClient);
recyclerProduct.setAdapter(adapter);
}
private void setupBillingClient() {
billingClient = BillingClient.newBuilder(this).setListener(this).enablePendingPurchases().build();
billingClient.startConnection(new BillingClientStateListener() {
#Override
public void onBillingSetupFinished(BillingResult billingResult) {
if(billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK){
Toast.makeText(InformationActivity.this,"Sucessfully Billing Connect",Toast.LENGTH_SHORT);
}else {
Toast.makeText(InformationActivity.this,"Failed to Billing Connect"+billingResult.getResponseCode(),Toast.LENGTH_SHORT);
}
}
#Override
public void onBillingServiceDisconnected() {
Toast.makeText(InformationActivity.this,"You are disconnected from billing",Toast.LENGTH_SHORT);
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
startActivity(new Intent(com.test.smartbuyapp.InformationActivity.this, ListMainActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
return true;
}
return false;
}
public void PrivacyPerform(View view) {
TextView agb = (TextView) findViewById(R.id.AGB);
agb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://sites.google.com/view/smartbuyapp/"));
startActivity(intent);
}
});
}
#Override
public void onPurchasesUpdated(BillingResult billingResult, #Nullable List<Purchase> list) {
//Here if user clicks Buy, we will receive data
Toast.makeText(InformationActivity.this,"Purchase item",Toast.LENGTH_SHORT);
}
}

How to send Data when cardview clicked to detail content

I try to passing data from cardview when clicked to DetailFragment, in this case I try to use interface in my adapter, but I get an error a null object reference in mOnItemClickListener.onClick(i).
I try to passing data from cardview when clicked to DetailFragment, in this case I try to use interface in my adapter.
I want to passing data to DetailMoviesFragment Class.
this is my CardviewMovieAdapter Class
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.RecyclerView;
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 com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import java.util.ArrayList;
public class CardviewMovieAdapter extends RecyclerView.Adapter<CardviewMovieAdapter.CardViewViewHolder> {
private ArrayList<Movie> listMovie;
Context context;
OnItemClickListener mOnItemClickListener;
public void setListMovie(ArrayList<Movie> listMovie) {
this.listMovie = listMovie;
}
public ArrayList<Movie> getListMovie() {
return listMovie;
}
public interface OnItemClickListener {
void onClick(int position);
}
public void setOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mOnItemClickListener = mItemClickListener;
}
public CardviewMovieAdapter(ArrayList<Movie> listMovie, Context context) {
this.listMovie = listMovie;
this.context = context;
}
#NonNull
#Override
public CardviewMovieAdapter.CardViewViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_movie, viewGroup,false);
return new CardViewViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final CardviewMovieAdapter.CardViewViewHolder cardViewViewHolder, final int i) {
final Movie movie = listMovie.get(i);
Glide.with(cardViewViewHolder.itemView.getContext())
.load(movie.getImageMovie())
.apply(new RequestOptions().override(350, 550))
.into(cardViewViewHolder.imgPhoto);
cardViewViewHolder.tvTitle.setText(movie.getTitleMovie());
cardViewViewHolder.tvDesc.setText(movie.getDescription());
cardViewViewHolder.btnDetail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(cardViewViewHolder.itemView.getContext(), "Detail "+
listMovie.get(cardViewViewHolder.getAdapterPosition()).getTitleMovie(), Toast.LENGTH_SHORT).show();
}
});
cardViewViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(cardViewViewHolder.itemView.getContext(), "Kamu Memilih "+movie.getTitleMovie(), Toast.LENGTH_SHORT).show();
mOnItemClickListener.onClick(i);
}
});
// cardViewViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// Toast.makeText(cardViewViewHolder.itemView.getContext(), "Kamu Memilih "+movie.getTitleMovie(), Toast.LENGTH_SHORT).show();
// }
// });
}
#Override
public int getItemCount() {
return listMovie.size();
}
public class CardViewViewHolder extends RecyclerView.ViewHolder {
ImageView imgPhoto;
TextView tvTitle, tvDesc;
Button btnDetail;
public CardViewViewHolder(#NonNull View itemView) {
super(itemView);
imgPhoto = itemView.findViewById(R.id.img_item_photo);
tvTitle = itemView.findViewById(R.id.tv_title);
tvDesc = itemView.findViewById(R.id.tv_desc);
btnDetail = itemView.findViewById(R.id.btn_detail);
}
}
}
This is my MoviesFragment Class
import android.content.Intent;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.CardView;
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.Button;
import android.widget.ListView;
import java.util.ArrayList;
/**
* A simple {#link Fragment} subclass.
*/
public class MoviesFragment extends Fragment implements View.OnClickListener{
private RecyclerView rvMovie;
private String[] dataMovieTitle;
private String[] dataDescription;
private TypedArray dataPhoto;
private ArrayList<Movie> movies;
Button btnDetail;
private CardviewMovieAdapter adapter;
View view;
final static String KEY = "KEY";
public MoviesFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_movies, container, false);
//adapter = new CardviewMovieAdapter(movies,getContext());
rvMovie = view.findViewById(R.id.rv_movies);
prepare();
addItem();
showRecyclerCardView();
adapter = new CardviewMovieAdapter(movies, getContext());
adapter.setOnItemClickListener(new CardviewMovieAdapter.OnItemClickListener() {
#Override
public void onClick(int position) {
final Movie movie = movies.get(position);
DetailMoviesFragment detailMoviesFragment = new DetailMoviesFragment();
// Bundle mBundle = new Bundle();
// mBundle.putString(detailMoviesFragment.EXTRA_TITLE, movie.getTitleMovie());
// mBundle.putString(detailMoviesFragment.EXTRA_DESCRIPTION, movie.getDescription());
// mBundle.putInt(detailMoviesFragment.EXTRA_PHOTO, movie.getImageMovie());
// detailMoviesFragment.setArguments(mBundle);
MoviesFragment.newInstance(movie.getTitleMovie(), movie.getDescription(), movie.getImageMovie());
FragmentManager mFragmentManager = getFragmentManager();
if (mFragmentManager!= null) {
FragmentTransaction mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containterFragment, detailMoviesFragment, DetailMoviesFragment.class.getSimpleName());
mFragmentTransaction.addToBackStack(null);
mFragmentTransaction.commit();
}
}
});
return view;
}
public static MoviesFragment newInstance(String title, String desc, int image) {
MoviesFragment moviesFragment = new MoviesFragment();
Bundle args = new Bundle();
args.putInt("image", image);
args.putString("title", title);
args.putString("desc", desc);
moviesFragment.setArguments(args);
return moviesFragment;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
private void showRecyclerCardView(){
rvMovie.setLayoutManager(new LinearLayoutManager(getActivity()));
CardviewMovieAdapter adapter = new CardviewMovieAdapter(movies,getActivity());
rvMovie.setAdapter(adapter);
}
private void prepare() {
dataMovieTitle = getResources().getStringArray(R.array.data_movie_name);
dataDescription = getResources().getStringArray(R.array.data_desc_movie);
dataPhoto = getResources().obtainTypedArray(R.array.data_photo_movie);
}
private void addItem(){
movies = new ArrayList<>();
for (int i=0; i < dataMovieTitle.length; i++){
Movie movie = new Movie();
movie.setImageMovie(dataPhoto.getResourceId(i, -1));
movie.setTitleMovie(dataMovieTitle[i]);
movie.setDescription(dataDescription[i]);
movies.add(movie);
}
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.card_view){
}
}
}
and this is DetailMoviesActivity Class
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
public class DetailMovieActivity extends AppCompatActivity {
Movie movie;
TextView tvTitle, tvDesc;
ImageView ivMovie;
Button btnDetail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail_movie);
initView();
}
private void initView() {
movie = (Movie) getIntent().getSerializableExtra("informasi");
String judul = movie.getTitleMovie();
String desc = movie.getDescription();
int img = movie.getImageMovie();
tvTitle.setText(judul);
tvDesc.setText(desc);
Picasso.get().load(img).into(ivMovie);
}
}
You can try with delete the setOnItemClickListener and call intent from cardViewViewHolder.itemView.setOnClickListener

Getting error index out of bound exception in my recyclerview

I'm trying to get favourite items in favourite list from main list.When i click on favourite icon in mainlist, favouritelist get updating but when i remove any favourite from favouritelist and trying to add more favourites from mainlist i get error index out of bound exception
MainActivity
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends AppCompatActivity implements RecyclerViewClickListener{
RecyclerView simpleListView;
static Context ctx;
String diseaseList[];
SharedPreference sharedPreference;
DiseaseAdapter da;
List<String> newDiseaseList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ctx=this;
sharedPreference = new SharedPreference();
diseaseList= new String[]{"Abscess",
"Allergies",
"Amnesia",
"Anemia",
"Andropause",
"Angina",
"Weight Loss"};
Arrays.sort(diseaseList);
newDiseaseList = Arrays.asList(diseaseList);
simpleListView= (RecyclerView)findViewById(R.id.simpleListView);
LinearLayoutManager lm=new LinearLayoutManager(MainActivity.this);
simpleListView.setLayoutManager(lm);
/* DividerItemDecoration di=new DividerItemDecoration(MainActivity.this,lm.getOrientation());
simpleListView.addItemDecoration(di);*/
da=new DiseaseAdapter(newDiseaseList,ctx,this);
simpleListView.setAdapter(da);
simpleListView.setHasFixedSize(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_favorites:
Intent i=new Intent(this,Favourite.class);
this.startActivity(i);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume() {
super.onResume();
da.notifyDataSetChanged();
}
#Override
public void recyclerViewListClicked(View view, int position) {
ImageView button = (ImageView) view.findViewById(R.id.imgbtn_favorite);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(ctx, newDiseaseList.get(position));
Toast.makeText(ctx,
"add to favourites",
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.star_colour);
} else {
sharedPreference.removeFavorite(ctx, newDiseaseList.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.ic_action_name);
Toast.makeText(ctx,
"removed from favourites",
Toast.LENGTH_SHORT).show();
}
}
}
Favourite.java
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.Collections;
import java.util.List;
public class Favourite extends AppCompatActivity implements RecyclerViewClickListener {
RecyclerView favoriteList;
SharedPreference sharedPreference;
List<String> favorites;
DiseaseAdapter diseaseAdapter;
static Context ctx;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favourite);
ctx=this;
sharedPreference = new SharedPreference();
favorites = sharedPreference.getFavorites(ctx);
Collections.sort(favorites);
favoriteList = (RecyclerView)findViewById(R.id.favListView);
LinearLayoutManager lm=new LinearLayoutManager(ctx);
favoriteList.setLayoutManager(lm);
favoriteList.setHasFixedSize(true);
if (favorites == null) {
showAlert(getResources().getString(R.string.no_favorites_items),
getResources().getString(R.string.no_favorites_msg));
} else {
if (favorites.size() == 0) {
showAlert(
getResources().getString(R.string.no_favorites_items),
getResources().getString(R.string.no_favorites_msg));
}
if (favorites != null) {
diseaseAdapter = new DiseaseAdapter(favorites,ctx,this);
favoriteList.setAdapter(diseaseAdapter);
}
}
}
public void showAlert(String title, String message) {
if (ctx != null) {
AlertDialog alertDialog = new AlertDialog.Builder(ctx)
.create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setCancelable(false);
// setting OK Button
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
// activity.finish();
getFragmentManager().popBackStackImmediate();
}
});
alertDialog.show();
}
}
#Override
public void recyclerViewListClicked(View view, int position) {
ImageView button = (ImageView) view
.findViewById(R.id.imgbtn_favorite);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(ctx,
favorites.get(position));
Toast.makeText(
ctx,
ctx.getResources().getString(
R.string.add_favr),
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.star_colour);
} else {
sharedPreference.removeFavorite(ctx,
favorites.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.ic_action_name);
/* diseaseAdapter.remove(favorites
.get(position));*/
diseaseAdapter.remove(position);
Toast.makeText(
ctx,
ctx.getResources().getString(
R.string.remove_favr),
Toast.LENGTH_SHORT).show();
}
}
}
Adapter
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
/**
* Created by admin on 12/4/2017.
*/
public class DiseaseAdapter extends RecyclerView.Adapter<DiseaseAdapter.DiseaseAdapterViewHolder> {
List <String> data;
Context ctx;
private static RecyclerViewClickListener itemListener;
SharedPreference sharedPreference;
DiseaseAdapter(List <String> data, Context ctx, RecyclerViewClickListener itemListener){
this.data=data;
this.ctx=ctx;
sharedPreference = new SharedPreference();
this.itemListener = itemListener;
notifyDataSetChanged();
}
#Override
public DiseaseAdapterViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater=LayoutInflater.from(parent.getContext());
View view= inflater.inflate(R.layout.activity_listview,parent,false);
return new DiseaseAdapterViewHolder(view);
}
#Override
public void onBindViewHolder(DiseaseAdapterViewHolder holder, int position) {
final String title=data.get(position);
holder.textView1.setText(title);
if (checkFavoriteItem(title)) {
holder.imageButton.setImageResource(R.drawable.star_colour);
holder.imageButton.setTag("red");
} else {
holder.imageButton.setImageResource(R.drawable.ic_action_name);
holder.imageButton.setTag("grey");
}
}
#Override
public int getItemCount() {
return data.size();
}
class DiseaseAdapterViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView textView1;
ImageView imageButton;
public DiseaseAdapterViewHolder(View itemView) {
super(itemView);
textView1=(TextView) itemView.findViewById(R.id.textView);
imageButton=(ImageView)itemView.findViewById(R.id.imgbtn_favorite);
imageButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
notifyDataSetChanged();
itemListener.recyclerViewListClicked(v, this.getLayoutPosition());
}
}
/*Checks whether a particular product exists in SharedPreferences*/
public boolean checkFavoriteItem(String checkProduct) {
boolean check = false;
List<String> favorites = sharedPreference.getFavorites(ctx);
if (favorites != null) {
for (String product : favorites) {
if (product.equals(checkProduct)) {
check = true;
break;
}
}
}
return check;
}
public void add(String product) {
data.add(product);
notifyDataSetChanged();
}
public void remove(int position) {
data.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, data.size());
notifyDataSetChanged();
}
}
SharedPreference
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import com.google.gson.Gson;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SharedPreference {
public static final String PREFS_NAME = "PRODUCT_APP";
public static final String FAVORITES = "Product_Favorite";
public SharedPreference() {
super();
}
// This four methods are used for maintaining favorites.
public void saveFavorites(Context context, List<String> favorites) {
SharedPreferences settings;
Editor editor;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
editor = settings.edit();
Gson gson = new Gson();
String jsonFavorites = gson.toJson(favorites);
editor.putString(FAVORITES, jsonFavorites);
editor.commit();
}
public void addFavorite(Context context, String product) {
List<String> favorites = getFavorites(context);
if (favorites == null)
favorites = new ArrayList<String>();
favorites.add(product);
saveFavorites(context, favorites);
}
public void removeFavorite(Context context, String product) {
List<String> favorites = getFavorites(context);
if (favorites != null) {
favorites.remove(product);
saveFavorites(context, favorites);
}
}
public ArrayList<String> getFavorites(Context context) {
SharedPreferences settings;
List<String> favorites ;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
if (settings.contains(FAVORITES)) {
String jsonFavorites = settings.getString(FAVORITES, null);
Gson gson = new Gson();
String [] favoriteItems = (gson.fromJson(jsonFavorites,String [].class));
favorites = Arrays.asList(favoriteItems);
favorites = new ArrayList<String>(favorites);
} else
return null;
return (ArrayList<String>) favorites;
}
}
This is an error that i'm getting
FATAL EXCEPTION: main
Process: com.example.admin.fav, PID: 10974
java.lang.IndexOutOfBoundsException: Invalid index 3, size is 3
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at com.example.admin.fav.Favourite.recyclerViewListClicked(Favourite.java:145)
at com.example.admin.fav.DiseaseAdapter$DiseaseAdapterViewHolder.onClick(DiseaseAdapter.java:90)
at android.view.View.performClick(View.java:5207)
at android.view.View$PerformClick.run(View.java:21168)
at android.os.Handler.handleCallback(Handler.java:746)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Problem in your listener. You are using same adapter class for both MainActivity recylerview & Favourite activity recylerview. After you go back from favourite activity to Mainactivity still your listener read from Favourite activity. Thats the issue.
Solution
Create Static field to hold listener value here am created in SharedPreference Class:
public class SharedPreference {
public static final String PREFS_NAME = "PRODUCT_APP";
public static final String FAVORITES = "Product_Favorite";
/*Added*/
private static RecyclerViewClickListener listener;
public RecyclerViewClickListener getListener() {
return listener;
}
public void setListener(RecyclerViewClickListener listener) {
SharedPreference.listener = listener;
}
/*Added*/
...
}
Add this code to MainActivity & Favourite Activity 'OnCreate' method
sharedPreference.setListener(this);
public class MainActivity extends AppCompatActivity implements RecyclerViewClickListener{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreference.setListener(this);
....
}
public class Favourite extends AppCompatActivity implements RecyclerViewClickListener{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favourite);
sharedPreference.setListener(this);
....
}
Change Adapter 'OnClick method' to
#Override
public void onClick(View v) {
notifyDataSetChanged();
itemListener = sharedPreference.getListener();
itemListener.recyclerViewListClicked(v, this.getLayoutPosition());
}
And Finally change in MainActivity 'resume' method
#Override
protected void onResume() {
super.onResume();
sharedPreference.setListener(this);
da.notifyDataSetChanged();
}
Hope it helps.!
In your DiseaseAdapterViewHolder change the onclick methode to,
#Override
public void onClick(View v) {
itemListener.recyclerViewListClicked(v, this.getLayoutPosition());
notifyDataSetChanged();
}

Categories

Resources