Unable to update TextView field inside RecyclerView - android

I'm migrating from ListView to an RecyclerView and last thing I'm stuck with is updating one of fields. My App has a simple list with some images found on internet. When you choose one, image gets downloaded to a phone for later offline viewing. Adapter gets data from SQLite databaseso when you tap on some image database gets updated (text changes from a "Tap here to Download" to a "Downloaded") and RecyclerView should follow.
I had same problem with ListView but there I just called populateList(); each time App updated db. I know it's not the ideal solution but it worked. Now I want to do it right with notifyDataSetChanged() or even better notifyItemChanged(position) but I can't get it working.
Anyway here's the code, sorry for being a little bit messy. This is just a test code (RecyclerView code is from samples):
public class RecyclerFragment extends Fragment {
private imgAdapter mAdapter;
private DatabaseHandler db;
private ProgressDialog mProgressDialog;
public RecyclerFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
db = new DatabaseHandler(getActivity());
List<Images> listdb = db.getImages();
mAdapter = new ImgAdapter(getActivity(), listdb);
db.close();
View view = inflater.inflate(R.layout.fragment_main, container, false);
RecyclerView recyclerView = (RecyclerView) view.findViewById(android.R.id.list);
recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new GridLayoutManager(
getActivity(), getResources().getInteger(R.integer.list_columns)));
recyclerView.setAdapter(mAdapter);
return view;
}
private class ImgAdapter extends RecyclerView.Adapter<ViewHolder>
implements ItemClickListener {
public List<Images> mList;
private Context mContext;
public ImgAdapter(Context context, List<Images> listdb) {
super();
mContext = context;
mList = listdb;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View view = inflater.inflate(R.layout.list_row1, parent, false);
return new ViewHolder(view, this);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
Images image = mList.get(position);
holder.mTitle.setText(image.getTitle());
holder.mDownloadStatus.setText(image.getDownloadStatus());
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemCount() {
return mList == null ? 0 : mList.size();
}
#Override
public void onItemClick(View view, int position) {
switch (position) {
case 0:
Log.v("POSITION 0:", " " + position);
break;
case 1:
/*
some logic nvm
*/
String imgurl = "http:/...";
String imagename = "Second image";
new GetImages(imgurl, imagename).execute();
/*
I've tried mAdapter.notitfy... , no luck aswell
This does nothing:
*/
notifyItemChanged(position);
notifyDataSetChanged();
break;
//....
}
}
}
private static class ViewHolder extends RecyclerView.ViewHolder
implements View.OnClickListener {
TextView mTitle;
TextView mDownloadStatus;
ItemClickListener mItemClickListener;
public ViewHolder(View view, ItemClickListener itemClickListener) {
super(view);
mTitle = (TextView) view.findViewById(R.id.text1);
mDownloadStatus = (TextView) view.findViewById(R.id.text2);
mItemClickListener = itemClickListener;
view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
mItemClickListener.onItemClick(v, getPosition());
}
}
interface ItemClickListener {
void onItemClick(View view, int position);
}
/*
This is my AsyncTask class used for downloading image and updating db
I removed some code just to to make it cleaner
*/
private class GetImages extends AsyncTask<Object, Object, Object> {
private final String requestUrl;
private final String imagename_;
private String imagename;
public int numberofbits;
private GetImages(String requestUrl, String _imagename_) {
this.requestUrl = requestUrl;
this.imagename_ = _imagename_;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//pDialog...
}
#Override
protected Object doInBackground(Object... objects) {
try {
URL url = new URL(requestUrl);
URLConnection conn = url.openConnection();
bitmap = BitmapFactory.decodeStream(conn.getInputStream());
numberofbits = bitmap.getByteCount();
} catch (Exception ignored) {
}
return null;
}
#Override
protected void onPostExecute(Object o) {
if (!ImageStorage.checkifImageExists(imagename)) {
ImageStorage.saveToSdCard(bitmap, imagename_);
}
if (numberofbits > 50) {
db = new DatabaseHandler(getActivity());
db.updateImages(new Images(dbid, "Downloaded", imagename_));
db.close();
//populateList(); -> THIS I USED FOR A LISTVIEW
Toast.makeText(getActivity(), "Downloaded!", Toast.LENGTH_SHORT).show();
mProgressDialog.dismiss();
//If image gets downloaded open it in Viewer class
Intent intent = new Intent(getActivity(), DisplayImage.class);
intent.putExtra("imagePath", path);
startActivity(intent);
} else {
//Toast.makeText(getActivity(), "Unable to download", Toast.LENGTH_SHORT).show();
mProgressDialog.dismiss();
}
}
}
}
Here's Images class
public class Images {
//private variables
private int _id;
private String _title;
private String _downloadstatus;
// Empty constructor
public Images () {
}
// constructor
public Images(int id, String title, String downloadstatus) {
this._id = id;
this._title = title;
this._downloadstatus = downloadstatus;
}
public int getID() {
return this._id;
}
public void setID(int id) {
this._id = id;
}
public String getTitle() {
return this._title;
}
public void setTitle(String title) {
this._title = title;
}
public String getDownloadStatus() {
return this._downloadstatus;
}
public void setDownloadStatus(String downloadstatus) {
this._downloadstatus = downloadstatus;
}
}
And here's an XML (I'm trying to update "text2"):
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:foreground="?attr/selectableItemBackground"
android:layout_height="wrap_content"
android:padding="8dp">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="match_parent"
>
<TextView
android:id="#+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="#dimen/imagename"
android:textStyle="bold"
android:paddingStart="4sp"
android:paddingEnd="40sp" />
<TextView
android:id="#+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/text1"
android:textSize="#dimen/downloaded"
android:paddingStart="4sp"
android:paddingEnd="1sp"
android:textColor="#color/graydownloaded" />
</RelativeLayout>
</FrameLayout>

Okay I finally got it working and It was actually quite simple...
//....
if (numberofbits > 50) {
db = new DatabaseHandler(getActivity());
db.updateImages(new Images(dbid, "Downloaded", imagename_));
//This is what I added:
List<Images> listdb = db.getImages();
mAdapter = new ImgAdapter(getActivity(), listdb);
recyclerView.setAdapter(mAdapter);
db.close();
//populateList(); -> THIS I USED FOR A LISTVIEW
Toast.makeText(getActivity(), "Downloaded!", Toast.LENGTH_SHORT).show();
mProgressDialog.dismiss();
//If image gets downloaded open it in Viewer class
Intent intent = new Intent(getActivity(), DisplayImage.class);
intent.putExtra("imagePath", path);
startActivity(intent);
} else {
//...

Try doing this: Override in your adapter the getItemId method like this
#Override
public long getItemId(int position) {
return mList.get(position).getID();
}
And add this line after recyclerView.setHasFixedSize(true) :
recyclerView.setHasStableId(true);
EDIT:
mAdapter.setHasStableId(true);
Let me know if that did the trick.

Related

Transferring data into a separate ArrayList and displaying in RecyclerView

I have two ArrayLists from which I am trying to insert data into separate static ArrayList in another class and display in RecyclerView, but the recycler is not getting populated though the same was being done with a dummy ArrayList.Please help me with this problem.
My Class where I am inserting data from phoneContactNos and phoneContactName in two separate ArrayList: Common.selectedContactNos and Common.selectedContactName.
public void displayMatchedContacts()
{
try {
for (int i = 1; i < phoneContactNos.size(); i++) {
if (phoneContactNos.contains(registeredContactNos.get(i))) {
if (registeredContactNos.get(i) != null) {
try {
indexOfRegNumber = phoneContactNos.indexOf(registeredContactNos.get(i));
//Common.indexPosition_contacts=indexOfRegNumber;
Toast.makeText(this, "index" + String.valueOf(indexOfRegNumber), Toast.LENGTH_LONG).show();
if ((phoneContactNos.get(indexOfRegNumber) != null) &&(phoneContactName.get(indexOfRegNumber) != null)) {
//String regName="";
//String regContact="";
Common.selectedContactNos.add(phoneContactNos.get(indexOfRegNumber));
//Toast.makeText(this,selectedContactNos.get(i).toString(),Toast.LENGTH_SHORT).show();
//Toast.makeText(this,phoneContactNos.get(indexOfRegNumber).toString(),Toast.LENGTH_SHORT).show();
Common.selectedContactName.add(phoneContactName.get(indexOfRegNumber));
//Toast.makeText(this,selectedContactName.get(i).toString(),Toast.LENGTH_SHORT).show();
//Toast.makeText(this, phoneContactName.get(indexOfRegNumber).toString(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "null index no", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Log.i("Contacts display error", e.getLocalizedMessage());
e.printStackTrace();
}
}
}
}
}catch (Exception e)
{
Log.i("Contacts error in loop", e.getLocalizedMessage());
e.printStackTrace();
}
}
My Common class
public final class Common {
public static ArrayList<String> selectedContactNos=new ArrayList<>();
public static ArrayList<String> selectedContactName=new ArrayList<>();
public static String fcmId="";
public static int position;
public static String contacts_list="";
public static int indexPosition_contacts;
}
My RecyclerView populating code
public void populateList() {
Log.i("Populate List","Entered");
LinearLayoutManager mLinearLayoutManager = new LinearLayoutManager(this);
recyclerView_contacts.setLayoutManager(mLinearLayoutManager);
displayRecyclerAdapter = new DisplayRecyclerAdapter(this);
recyclerView_contacts.setAdapter(displayRecyclerAdapter);
}
My Adapter Class
public class DisplayRecyclerAdapter extends RecyclerView.Adapter<DisplayRecyclerAdapter.displayViewHolder> {
private LayoutInflater mInflater;
private Context context;
Fragment fragment;
FragmentTransaction ft;
FrameLayout container;
public DisplayContacts displayContacts;
public DisplayRecyclerAdapter(Context context) {
this.mInflater = LayoutInflater.from(context);
this.context = context;
ft = ((AppCompatActivity) context).getSupportFragmentManager().beginTransaction();
//displayContacts = new DisplayContacts();
}
#Override
public displayViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.contacts_row, parent, false);
displayViewHolder holder = new displayViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(displayViewHolder holder, int position) {
holder.setData(position);
//Common.position = position;
holder.setListeners();
//for(int i=0;i<((DisplayContacts)context).selectedContactName.size();i++)
for(int i=0;i<Common.selectedContactName.size();i++)
{
//String contactName=((DisplayContacts)context).selectedContactName.get(i);
String contactName=Common.selectedContactName.get(i);
//String contactNumber=((DisplayContacts)context).selectedContactNos.get(i);
String contactNumber=Common.selectedContactNos.get(i);
Toast.makeText(context,contactName+","+contactNumber,Toast.LENGTH_SHORT).show();
}
}
class displayViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
int position;
//ImageView productSearchImg;
TextView name_contactList;
Button call_contact;
public displayViewHolder(View itemView) {
super(itemView);
name_contactList = (TextView) itemView.findViewById(R.id.contactlist_name);
call_contact = (Button) itemView.findViewById(R.id.contactlist_call);
}
public void setData(int position) {
this.position = position;
//String displayContacts=((DisplayContacts) context).selectedContactName.get(position);
String displayContacts=Common.selectedContactName.get(position);
Toast.makeText(context,"name to display"+ displayContacts,Toast.LENGTH_SHORT).show();
//name_contactList.setText(((DisplayContacts) context).selectedContactName.get(position));
//name_contactList.setText(displayContacts);
name_contactList.setText("dummy text");
}
#Override
public void onClick(View v) {
//sendPushNotification();
startAudioCall();
}
public void setListeners() {
call_contact.setOnClickListener(displayViewHolder.this);
}
}
public void startAudioCall() {
Intent i = new Intent(context, AudioCallActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
#Override
public int getItemCount() {
return ((DisplayContacts) context).selectedContactName.size();
}
}
can be one of two things:
1.you are not attaching the adapter with data,hence empty
2.or you are updating your data but not calling notifyDataSetChanged()
try to pass the list data in your Adapter class while you are creating it,then attach it to the recyelerview.
//to give a vary basic example
List dataList;
RvAdapter(Context c,List data){
this.dataList=data;
}
onBidViewHolder(Viewholder holder,int position){
holder.tvName.setText(dataList.get(position).getName());
.......
}
//in your activity/fragment
RvAdapter adapter=new RavAdapter(context,dataList);
recylerview.setAdapter(adapter);
//if you change your data
adapter.notifyDataSetChanged()

RecyclerView having trouble displaying Empty case

I am trying to display an Empty view in an app that displays movie posters. I am using a recyclerview - for example when I put my device in flight mode and click refresh I was expecting the app to display the empty state view but this is not the case.
The posters are still displayed in the Activity. Why is this the case?
The data is from the moviedatabase api & I am retrieving a movie title & relative image path
MAIN ACTIVITY
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<List<Movie>> {
private static final String LOG_TAG = MainActivity.class.getSimpleName();
private static final int LOADER_ID = 1;
private MovieAdapter mMovieAdapter;
private RecyclerView mRecyclerView;
private GridLayoutManager mGridLayoutManager;
private LoaderManager mLoaderManager;
private View mLoadingIndicator;
private TextView mEmptyTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mLoadingIndicator = findViewById(R.id.loadingIndicator);
mEmptyTextView = (TextView) findViewById(R.id.emptyStateTextView);
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mLoadingIndicator.setVisibility(View.VISIBLE);
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mGridLayoutManager = new GridLayoutManager(this, 2);
mRecyclerView.setLayoutManager(mGridLayoutManager);
mMovieAdapter = new MovieAdapter();
mRecyclerView.setAdapter(mMovieAdapter);
mLoaderManager = getSupportLoaderManager();
mLoaderManager.initLoader(LOADER_ID, null, this);
}
public void showMovieDataView() {
mEmptyTextView.setVisibility(View.INVISIBLE);
mRecyclerView.setVisibility(View.VISIBLE);
}
public void showErrorMessage() {
mRecyclerView.setVisibility(View.INVISIBLE);
mEmptyTextView.setVisibility(View.VISIBLE);
}
#Override
public Loader<List<Movie>> onCreateLoader(int id, Bundle args) {
return new MovieLoader(this, TmdbUrlUtils.BASE_URL);
}
#Override
public void onLoadFinished(Loader<List<Movie>> loader, List<Movie> data) {
mLoadingIndicator.setVisibility(View.INVISIBLE);
if (data == null) {
showErrorMessage();
} else {
showMovieDataView();
mMovieAdapter.setMovieData(data);
}
}
#Override
public void onLoaderReset(Loader<List<Movie>> loader) {
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.refresh:
mLoadingIndicator.setVisibility(View.VISIBLE);
mMovieAdapter.setMovieData(null);
getSupportLoaderManager().restartLoader(LOADER_ID, null, this);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
ADAPTER CLASS
public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.ViewHolder> {
List<Movie> mMovieList;
public static final String BASE_POSTER_URL = "http://image.tmdb.org/t/p/w185";
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Context context = holder.mImageView.getContext();
String imagePath = mMovieList.get(position).getmPosterPath();
Uri baseUri = Uri.parse(BASE_POSTER_URL);
Uri.Builder builder = baseUri.buildUpon();
builder.appendEncodedPath(imagePath);
String imageUrl = builder.toString();
Picasso.with(context).load(imageUrl).into(holder.mImageView);
}
#Override
public int getItemCount() {
if (null == mMovieList) return 0;
return mMovieList.size();
}
public void setMovieData(List<Movie> data) {
mMovieList = data;
this.notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public ImageView mImageView;
public ViewHolder(View itemView) {
super(itemView);
mImageView = (ImageView) itemView.findViewById(R.id.imagePoster);
}
}
}
ACTIVITY_MAIN XML
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f48fb1"
tools:context="com.example.android.cinemate.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#d4e157">
</android.support.v7.widget.RecyclerView>
<ProgressBar
android:id="#+id/loadingIndicator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:visibility="invisible"/>
<TextView
android:id="#+id/emptyStateTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#f44336"
android:text="No network detected!"
android:visibility="invisible"/>
</FrameLayout>
CUSTOM OBJECT
public class Movie implements Parcelable {
public static final Creator<Movie> CREATOR = new Creator<Movie>() {
#Override
public Movie createFromParcel(Parcel in) {
return new Movie(in);
}
#Override
public Movie[] newArray(int size) {
return new Movie[size];
}
};
private String mTitle;
private String mPosterPath;
public Movie(String title, String posterPath) {
this.mTitle = title;
this.mPosterPath = posterPath;
}
protected Movie(Parcel in) {
mTitle = in.readString();
mPosterPath = in.readString();
}
public String getmTitle() {
return mTitle;
}
public void setmTitle(String mTitle) {
this.mTitle = mTitle;
}
public String getmPosterPath() {
return mPosterPath;
}
public void setmPosterPath(String mPosterPath) {
this.mPosterPath = mPosterPath;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(mTitle);
parcel.writeString(mPosterPath);
}
}
This is a LOG of what gets called when flight mode is on:
Refresh selected with Flight Mode on
TEST......MainActivity onCreateLoader() called
TEST.......MovieLoader loadInBackground() called
TEST.......NetworkUtils getDataFromNetwork() called
TEST.......NetworkUtils createUrl() called
TEST.......NetworkUtils makeHttpRequest() called
TEST.......MovieJsonUtils parseJson() called
TEST......MainActivity onLoadFinished() called
TEST......MainActivity showMovieData() called

RecyclerView notifyDatasetChanged not working

I have a RecyclerView inside a Fragment within Activity. I need to refresh my RecyclerView from Activity. I added a method inside Fragment which called notifyDatasetChanged to refresh RecyclerView. But notifyDatasetChanged didn't work.
Here is my Fragment.
public class CategoryFragment extends Fragment{
private RecyclerView recyclerView;
private EventsAdapter adapter;
static Context context = null;
private List<Category> categories;
private List<Item> allItems = new ArrayList();
private ReminderDatabase dbHandler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(!checkDatabase()){
copyDatabase();
}
context = getActivity();
dbHandler = new ReminderDatabase(context);
fillAllItems();
}
public void fillAllItems(){
categories = dbHandler.getAllCategory();
for(int i=0;i<categories.size();i++){
Category category = categories.get(i);
Item categoryItem = new Item(category.getTitle(),category.getColor(),Category.CATEGORY_TYPE);
allItems.add(categoryItem);
List<Event> events = dbHandler.getEventsByCategory(category.getTitle());
for(int j=0;j<events.size();j++){
Event e = events.get(j);
Item eventItem = new Item(e.getId(),e.getTitle(),e.getDescription(),e.getPlace(),e.getCategory(),e.getTime(),e.getDate(),categoryItem.getColor(),e.isShow(),Event.EVENT_TYPE);
allItems.add(eventItem);
}
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.category_fragment, container, false);
recyclerView = (RecyclerView) v.findViewById(R.id.recyclerView);
adapter = new EventsAdapter(getContext(),allItems);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(adapter);
return v;
}
public boolean checkDatabase(){
String path = "/data/data/com.example.materialdesign.reminder/databases/";
String filename = "Remind";
File file = new File(path+filename);
Log.d("Database","File exists -> "+file.exists());
return file.exists();
}
public void copyDatabase(){
String path = "/data/data/com.example.materialdesign.reminder/databases/Remind";
ReminderDatabase dbHandler = new ReminderDatabase(getContext());
dbHandler.getWritableDatabase();
InputStream fin;
OutputStream fout;
byte[] bytes = new byte[1024];
try {
fin = getActivity().getAssets().open("Remind");
fout = new FileOutputStream(path);
int length=0;
while((length = fin.read(bytes))>0){
fout.write(bytes,0,length);
}
fout.flush();
fout.close();
fin.close();
Log.d("Database","successfully copied database");
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.d("Database","-Error" +e.getMessage());
} catch (IOException e) {
e.printStackTrace();
Log.d("Database","-Error" +e.getMessage());
}
}
#Override
public void onResume() {
super.onResume();
allItems.clear();
Log.d("TAG","onresume");
fillAllItems();
adapter.notifyDataSetChanged();
}
public void refresh(){
Log.d("c",allItems.size()+"");
allItems.clear();
fillAllItems();
Log.d("c",allItems.size()+"");
adapter.notifyDataSetChanged();
}
}
I called refresh method from MainActivity.
#Override
public void onInserted() {
fragment.refresh();
}
My Adapter is here.
public class EventsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
private Context context;
private List<Item> allItems = new ArrayList();
private HideOrShowListener hideOrShowListener;
public static final int EVENT_TYPE = 1;
public static final int CATEGORY_TYPE = 0;
private int lastPosition;
private boolean flag = false;
public EventsAdapter(Context context,List<Item> allItems){
this.context = context;
hideOrShowListener =(HideOrShowListener) context;
this.allItems = allItems;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
switch (viewType){
case CATEGORY_TYPE:
view = LayoutInflater.from(context).inflate(R.layout.category_item,parent,false);
return new CategoryViewHolder(view);
case EVENT_TYPE:
view = LayoutInflater.from(context).inflate(R.layout.events_item,parent,false);
return new EventViewHolder(view);
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final Item item = allItems.get(position);
switch (item.getType()){
case CATEGORY_TYPE:
((CategoryViewHolder)holder).tvCategoryTitle.setText(item.getTitle());
((GradientDrawable)(((CategoryViewHolder)holder).categoryColorIcon).getBackground()).setColor(Color.parseColor(item.getColor()));
((CategoryViewHolder)holder).imgAddEvent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
hideOrShowListener.setHideOrShow(item,false);
}
});
break;
case EVENT_TYPE:
String[] time = item.getTime().trim().split(":");
int hour = Integer.parseInt(time[0]);
((EventViewHolder)holder).tvEventName.setText(item.getTitle());
((EventViewHolder)holder).tvTime.setText(hour<12?hour+" : "+time[1] +" am" : hour-12+" : "+time[1] +" pm" );
((EventViewHolder)holder).tvPlace.setText(item.getPlace());
if(item.getDescription().length()==0) {
item.setDescription("No Detail");
}
((EventViewHolder)holder).tvDescription.setText(item.getDescription());
if(item.isShow()){
((EventViewHolder)holder).descriptionLayout.animate().alpha(1).setDuration(200).setInterpolator(new AccelerateInterpolator()).start();
((EventViewHolder)holder).descriptionLayout.setVisibility(View.VISIBLE);
((EventViewHolder)holder).descriptionLayout.setSelected(true);
((EventViewHolder)holder).tvEdit.setVisibility(View.VISIBLE);
((EventViewHolder)holder).eventContainer.setSelected(true);
}else{
((EventViewHolder)holder).descriptionLayout.setVisibility(View.GONE);
((EventViewHolder)holder).descriptionLayout.animate().alpha(0).setDuration(500).start();
((EventViewHolder)holder).descriptionLayout.setSelected(false);
((EventViewHolder)holder).eventContainer.setSelected(false);
((EventViewHolder)holder).tvEdit.setVisibility(View.INVISIBLE);
}
((EventViewHolder)holder).tvEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
hideOrShowListener.setHideOrShow(item,true);
}
});
break;
}
}
#Override
public int getItemCount() {
Log.d("c",allItems.size()+"");
return allItems.size();
}
#Override
public int getItemViewType(int position) {
if(allItems!=null){
return allItems.get(position).getType();
}
return 0;
}
public class CategoryViewHolder extends RecyclerView.ViewHolder{
private TextView tvCategoryTitle;
private View categoryColorIcon;
private ImageView imgAddEvent;
public CategoryViewHolder(View itemView) {
super(itemView);
tvCategoryTitle = (TextView) itemView.findViewById(R.id.tvCategoryTitle);
categoryColorIcon = itemView.findViewById(R.id.categoryColorIcon);
imgAddEvent = (ImageView) itemView.findViewById(R.id.addEvent);
}
}
public class EventViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private LinearLayout descriptionLayout;
private RelativeLayout eventContainer;
private TextView tvEventName,tvTime,tvPlace,tvDescription,tvEdit;
public EventViewHolder(View itemView) {
super(itemView);
descriptionLayout = (LinearLayout) itemView.findViewById(R.id.descriptionLayout);
eventContainer = (RelativeLayout) itemView.findViewById(R.id.eventContainer);
tvEventName = (TextView) itemView.findViewById(R.id.tvEventName);
tvTime = (TextView) itemView.findViewById(R.id.tvTime);
tvPlace = (TextView) itemView.findViewById(R.id.tvPlace);
tvDescription = (TextView) itemView.findViewById(R.id.tvDescription);
tvEdit = (TextView) itemView.findViewById(R.id.tvEdit);
eventContainer.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(flag){
allItems.get(lastPosition).setShow(false);
}
allItems.get(getAdapterPosition()).setShow(true);
flag = true;
lastPosition = getAdapterPosition();
notifyDataSetChanged();
}
}
public interface HideOrShowListener{
public void setHideOrShow(Item item , boolean isEdit);
}
}
But when I click home button and reenter my application, my RecyclerView refresh. It means that notifyDatasetChanged in onResume method works. But in my refresh method, it doesn't work. How can I do this?
Are you sure this method is being called :
#Override
public void onInserted() {
fragment.refresh();
}
Make sure that you've a correct instance of the fragment. Or you can simply user interface with the refresh() method and implement it in the fragment.

Change the Icon of a Button in a Recycler View in Adapter Class Based off boolean value

I'm trying to change the icon of a button in my recycler view every time the activity starts based off a boolean value in my custom object. I assume this has to be done within the adapter since not every groups button will have the same background.
Below is the code for my recycler view adapter:
public class RecipeListAdapter extends RecyclerView.Adapter<RecipeListAdapter.ViewHolder>{
private List<Recipe> mRecipeSet;
private Button mAddToGroceriesButton;
public RecipeListAdapter(List<Recipe> recipes){
mRecipeSet = recipes;
}
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
//This is what will handle what happens when you click a recipe in the recycler view
private TextView mRecipeName;
private TextView mPrepTime;
private TextView mCookTime;
private TextView mServingSize;
private RelativeLayout mRecipeTextSection;
public ViewHolder(View v) {
super(v);
mRecipeName = (TextView) v.findViewById(R.id.recipe_list_recycler_view_recipe_name);
mServingSize = (TextView) v.findViewById(R.id.recipe_list_recycler_view_serving_size);
mPrepTime = (TextView) v.findViewById(R.id.recipe_list_recycler_view_prep_time);
mCookTime = (TextView) v.findViewById(R.id.recipe_list_recycler_view_cook_time);
mRecipeTextSection = (RelativeLayout) v.findViewById(R.id.recycled_item_section_view);
mRecipeTextSection.setOnClickListener(this);
mAddToGroceriesButton = (Button) v.findViewById(R.id.add_to_grocery_list);
mAddToGroceriesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
Recipe recipeToGrocery = mRecipeSet.get(position);
//RecipeDB dbHelper = new RecipeDB(v.getContext());
//dbHelper.addGroceryItem(recipeToGrocery);
if(!recipeToGrocery.isInList()) {
RecipeDB dbHelper = new RecipeDB(v.getContext());
dbHelper.addGroceryItem(recipeToGrocery);
recipeToGrocery.setInList(true);
dbHelper.updateRecipe(recipeToGrocery);
mAddToGroceriesButton.setBackgroundResource(R.mipmap.ic_playlist_add_check_black_24dp);
Toast.makeText(v.getContext(), recipeToGrocery.getRecipeName() + " added to grocery list.", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(v.getContext(), "That recipe is already in the list.", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onClick(View v){
int position = getAdapterPosition();
Intent i = new Intent(v.getContext(), RecipeTextView.class);
Recipe selectedRecipe = mRecipeSet.get(position);
i.putExtra("view_recipe_key", selectedRecipe);
v.getContext().startActivity(i);
}
}
public void add(int position, Recipe item) {
mRecipeSet.add(position, item);
notifyItemInserted(position);
}
public void remove(Recipe item) {
int position = mRecipeSet.indexOf(item);
mRecipeSet.remove(position);
notifyItemRemoved(position);
}
public RecipeListAdapter(ArrayList<Recipe> myRecipeset) {
mRecipeSet = myRecipeset;
}
// Create new views (invoked by the layout manager)
#Override
public RecipeListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recipe_item_recycled, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Recipe recipe = mRecipeSet.get(position);
String recipeName = recipe.getRecipeName();
String prepTime = "Prep Time: " + String.valueOf(recipe.getPrepTime()) + " minutes";
String cookTime = "Cook Time: " + String.valueOf(recipe.getCookTime()) + " minutes";
String servingSize = "Servings: " + String.valueOf(recipe.getServings());
holder.mRecipeName.setText(recipeName);
//Only display values if they are not null
if(recipe.getServings() != null) {
holder.mServingSize.setText(servingSize);
}
if (recipe.getPrepTime() != null) {
holder.mPrepTime.setText(prepTime);
}
if(recipe.getCookTime() != null) {
holder.mCookTime.setText(cookTime);
}
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
if(mRecipeSet != null) {
return mRecipeSet.size();
}
return 0;
}
}
I know how to change the background of the button when it's clicked with
mAddToGroceriesButton.setBackgroundResource(R.mipmap.ic_playlist_add_check_black_24dp);
but it's obviously not going to save the state of that button when the activity restarts. I'm just not sure of how to check the boolean value for each group upon activity start up and change the button background accordingly.
I tried using
if(recipe.isInList()){
mAddToGroceriesButton.setBackgroundResource(R.mipmap.ic_playlist_add_check_black_24dp);
}
in the onBindViewHolder method but it didn't do anything, and I'm pretty sure that wouldn't be the correct place for it anyways. I know the boolean is working properly since I use it in other places and it works fine.
Here's the relevant XML code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/apk/res/android"
android:layout_margin="7dp"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:id="#+id/recycled_item_section_view"
android:elevation="30dp"
android:background="#drawable/background_border"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:text="Recipe name"
android:textSize="24dp"
android:textColor="#color/black"
android:id="#+id/recipe_list_recycler_view_recipe_name"
android:paddingBottom="3dp"
android:maxWidth="275dip"
android:singleLine="false"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="18dp"
android:textColor="#color/black"
android:layout_below="#id/recipe_list_recycler_view_recipe_name"
android:id="#+id/recipe_list_recycler_view_serving_size"
android:paddingBottom="3dp"/>
<Button
android:layout_width="35dp"
android:layout_height="35dp"
android:background="#mipmap/ic_playlist_add_black_24dp"
android:height="36dp"
android:padding="8dp"
android:layout_alignParentRight="true"
android:id="#+id/add_to_grocery_list"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/recipe_list_recycler_view_serving_size"
android:layout_alignParentLeft="true"
android:textSize="18dp"
android:textColor="#color/black"
android:id="#+id/recipe_list_recycler_view_prep_time"
android:paddingBottom="3dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/recipe_list_recycler_view_prep_time"
android:textSize="18dp"
android:textColor="#color/black"
android:layout_alignParentLeft="true"
android:id="#+id/recipe_list_recycler_view_cook_time"/>
</RelativeLayout>
Recipe class:
public class Recipe implements Parcelable {
//These are all of the qualities a recipe contains, we will create an arraylist of this in the activity
private String mRecipeName;
private int mID;
private String mServings;
private String mPrepTime;
private String mCookTime;
private boolean isInList;
private List<String> mIngredients;
private List<String> mDirections;
public Recipe(){
}
public Recipe(int id, String name, String serving, String prep, String cook, List<String>
ingredientsList, List<String> directionsList, boolean inList){
this.mID = id;
this.mRecipeName = name;
this.mServings = serving;
this.mPrepTime = prep;
this.mCookTime = cook;
this.mIngredients = ingredientsList;
this.mDirections = directionsList;
this.isInList = inList;
}
public Recipe(String name, String serving, String prep, String cook, List<String>
ingredientsList, List<String> directionsList, boolean inList){
this.mRecipeName = name;
this.mServings = serving;
this.mPrepTime = prep;
this.mCookTime = cook;
this.mIngredients = ingredientsList;
this.mDirections = directionsList;
this.isInList = inList;
}
public String getRecipeName() {
return mRecipeName;
}
public int getID() {
return mID;
}
public void setID(int id){
mID = id;
}
public String getServings() {
return mServings;
}
public String getPrepTime() {
return mPrepTime;
}
public void setRecipeName(String recipeName) {
mRecipeName = recipeName;
}
public void setServingSize(String servings) {
mServings = servings;
}
public void setPrepTime(String prepTime) {
mPrepTime = prepTime;
}
public void setServings(String servings) {
mServings = servings;
}
public List<String> getIngredients() {
return mIngredients;
}
public List<String> getDirections() {
return mDirections;
}
public String getCookTime() {
return mCookTime;
}
public void setCookTime(String cookTime) {
mCookTime = cookTime;
}
public void setIngredients(List<String> ingredients) {
mIngredients = ingredients;
}
public void setDirections(List<String> directions) {
mDirections = directions;
}
public boolean isInList() {
return isInList;
}
public void setInList(boolean inList) {
isInList = inList;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.mRecipeName);
dest.writeInt(this.mID);
dest.writeString(this.mServings);
dest.writeString(this.mPrepTime);
dest.writeString(this.mCookTime);
dest.writeByte(this.isInList ? (byte) 1 : (byte) 0);
dest.writeStringList(this.mIngredients);
dest.writeStringList(this.mDirections);
}
protected Recipe(Parcel in) {
this.mRecipeName = in.readString();
this.mID = in.readInt();
this.mServings = in.readString();
this.mPrepTime = in.readString();
this.mCookTime = in.readString();
this.isInList = in.readByte() != 0;
this.mIngredients = in.createStringArrayList();
this.mDirections = in.createStringArrayList();
}
public static final Creator<Recipe> CREATOR = new Creator<Recipe>() {
#Override
public Recipe createFromParcel(Parcel source) {
return new Recipe(source);
}
#Override
public Recipe[] newArray(int size) {
return new Recipe[size];
}
};
}
And main activity class that uses the adapter:
public class RecipeList extends AppCompatActivity{
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private int REQUEST_CODE=1;
private Button mNavigateGroceryButton;
RecipeDB dbHelper = new RecipeDB(this);
List<Recipe> recipes;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
recipes = dbHelper.getAllRecipes();
setContentView(R.layout.activity_recipe_list);
mRecyclerView = (RecyclerView) findViewById(R.id.list_recycler_view);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new RecipeListAdapter(recipes);
mRecyclerView.setAdapter(mAdapter);
mNavigateGroceryButton = (Button) findViewById(R.id.navigate_to_groceries_button_list_view);
mNavigateGroceryButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
Intent i = new Intent(RecipeList.this, ExpandableListViewActivity.class);
//Log.d("Navigate", "navigate pressed" );
startActivity(i);
}
});
}
#Override
public void onBackPressed() {
}
public boolean onOptionsItemSelected(MenuItem item){
//Handles menu buttons
switch (item.getItemId()){
case R.id.recipe_list_add_recipe_actionbar_button:
//This button creates a new empty Recipe object and passes it to the EditRecipe class
//The Recipe object is passed as a parcelable
Recipe passedRecipe = new Recipe();
Intent i = new Intent(RecipeList.this, EditRecipe.class);
i.putExtra("passed_recipe_key", (Parcelable) passedRecipe);
startActivityForResult(i, REQUEST_CODE);
return true;
default:
Log.d("Name,", "default called");
return super.onOptionsItemSelected(item);
}
}
public void addNewReRecipe(Recipe recipe){
dbHelper.addRecipe(recipe);
recipes = dbHelper.getAllRecipes();
mAdapter = new RecipeListAdapter(recipes);
mRecyclerView.setAdapter(mAdapter);
}
//Makes the menu bar appear as it is in the action_bar_recipe_list_buttons menu layout file
#Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.action_bar_recipe_list_buttons, menu);
return true;
}
//This code is called after creating a new recipe. This is only for creating, and not editing.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE){
if(resultCode == Activity.RESULT_OK) {
Recipe createdRecipe = data.getExtras().getParcelable("recipe_key");
addNewReRecipe(createdRecipe);
}
}
}
}
Looks like you need to declare your button at the top of your ViewHolder with your other views. So move the declaration from the top of your adapter:
private Button mAddToGroceriesButton;
Then in your onBindViewHolder method you can get a reference to your button through the holder and set the background:
if(recipe.isInList()) {
holder.mAddToGroceriesButton.setBackgroundResource(R.mipmap.ic_playlist_add_check_black_24dp);
}
Try this,
public class RecipeListAdapter extends RecyclerView.Adapter<RecipeListAdapter.ViewHolder>{
private List<Recipe> mRecipeSet;
private Button mAddToGroceriesButton;
public RecipeListAdapter(List<Recipe> recipes){
mRecipeSet = recipes;
}
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
//This is what will handle what happens when you click a recipe in the recycler view
private TextView mRecipeName;
private TextView mPrepTime;
private TextView mCookTime;
private TextView mServingSize;
private RelativeLayout mRecipeTextSection;
public ViewHolder(View v) {
super(v);
mRecipeName = (TextView) v.findViewById(R.id.recipe_list_recycler_view_recipe_name);
mServingSize = (TextView) v.findViewById(R.id.recipe_list_recycler_view_serving_size);
mPrepTime = (TextView) v.findViewById(R.id.recipe_list_recycler_view_prep_time);
mCookTime = (TextView) v.findViewById(R.id.recipe_list_recycler_view_cook_time);
mRecipeTextSection = (RelativeLayout) v.findViewById(R.id.recycled_item_section_view);
mAddToGroceriesButton = (Button) v.findViewById(R.id.add_to_grocery_list);
}
}
public void add(int position, Recipe item) {
mRecipeSet.add(position, item);
notifyItemInserted(position);
}
public void remove(Recipe item) {
int position = mRecipeSet.indexOf(item);
mRecipeSet.remove(position);
notifyItemRemoved(position);
}
public RecipeListAdapter(ArrayList<Recipe> myRecipeset) {
mRecipeSet = myRecipeset;
}
// Create new views (invoked by the layout manager)
#Override
public RecipeListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recipe_item_recycled, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Recipe recipe = mRecipeSet.get(position);
String recipeName = recipe.getRecipeName();
String prepTime = "Prep Time: " + String.valueOf(recipe.getPrepTime()) + " minutes";
String cookTime = "Cook Time: " + String.valueOf(recipe.getCookTime()) + " minutes";
String servingSize = "Servings: " + String.valueOf(recipe.getServings());
holder.mRecipeName.setText(recipeName);
//Only display values if they are not null
if(recipe.getServings() != null) {
holder.mServingSize.setText(servingSize);
}
if (recipe.getPrepTime() != null) {
holder.mPrepTime.setText(prepTime);
}
if(recipe.getCookTime() != null) {
holder.mCookTime.setText(cookTime);
}
mRecipeTextSection.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
Intent i = new Intent(v.getContext(), RecipeTextView.class);
Recipe selectedRecipe = mRecipeSet.get(position);
i.putExtra("view_recipe_key", selectedRecipe);
v.getContext().startActivity(i);
});
Recipe recipeToGrocery = mRecipeSet.get(position);
if(!recipeToGrocery.isInList()) {
mAddToGroceriesButton.setBackgroundResource(R.mipmap.ic_playlist_add_check_black_24dp);
}
else{
mAddToGroceriesButton.setBackgroundResource(R.mipmap.ic_playlist_add_check_black_26dp);//set another image
}
mAddToGroceriesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
Recipe recipeToGrocery = mRecipeSet.get(position);
//RecipeDB dbHelper = new RecipeDB(v.getContext());
//dbHelper.addGroceryItem(recipeToGrocery);
if(!recipeToGrocery.isInList()) {
RecipeDB dbHelper = new RecipeDB(v.getContext());
dbHelper.addGroceryItem(recipeToGrocery);
recipeToGrocery.setInList(true);
dbHelper.updateRecipe(recipeToGrocery);
notifyDataSetChanged();
}
else {
Toast.makeText(v.getContext(), "That recipe is already in the list.", Toast.LENGTH_SHORT).show();
}
}
});
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
if(mRecipeSet != null) {
return mRecipeSet.size();
}
return 0;
}
}

How to get id of sqlite when recyclerview item clicked?

Here is my doubt when i click recyclerview item need to get task id which i saved in sqlite how can i do this for example when i click recycler view need to pass that value to next page and need update that value how can i do this so far what i have tried is:
public class Task extends Fragment {
private static final String MY_PREFERENCE_KEY = "yogan";
private List<Model_Task_List> model_task_lists;
private RecyclerView recyclerView;
Task_List_Adapter taskadapter;
private RecyclerView.LayoutManager layoutManager;
SharedPreferences sharedPreferences;
private RecyclerView.Adapter adapter;
RequestQueue yog;
String user_id;
AppController app;
RequestQueue queue;
String Url;
Task_DB task_db = null;
Database_SF_APP database_sf_app;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_task, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.my_recycler_view);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setLayoutManager(layoutManager);
if (model_task_lists == null) {
model_task_lists = new ArrayList<Model_Task_List>();
}
Calendar c = Calendar.getInstance();
System.out.println("Current time => " + c.getTime());
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = df.format(c.getTime());
int hour=c.get(Calendar.HOUR_OF_DAY);
String hours=Integer.toString(hour);
database_sf_app = new Database_SF_APP(getActivity().getBaseContext());
int count=database_sf_app.getTaskCount();
sharedPreferences = getActivity().getSharedPreferences(LoginActivity.login, 0);
user_id = sharedPreferences.getString("user_id", null);
model_task_lists=database_sf_app.getTaskListById(user_id);
taskadapter=new Task_List_Adapter(model_task_lists,getActivity());
recyclerView.setAdapter(taskadapter);
if(taskadapter!=null){
taskadapter.setOnItemClickListener(new Task_List_Adapter.data() {
#Override
public void yog(View v, int position) {
}
});
}
queue = Volley.newRequestQueue(getContext());
Url = "http://xxx.xx.x.xx/xxx/GetActivitiesByUserID.svc/getlist/Task/" + user_id +"/" +null+"/"+hours;
ConnectivityManager cn = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo nf = cn.getActiveNetworkInfo();
if (nf != null && nf.isConnected()) {
Toast.makeText(getActivity(), "Network Available", Toast.LENGTH_LONG).show();
JsonObjectRequest jsonObjRequest = new JsonObjectRequest(Request.Method.POST, Url, new JSONObject(),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
String server_response = response.toString();
try {
JSONObject json_object = new JSONObject(server_response);
JSONArray json_array = new JSONArray(json_object.getString("TaskResult"));
for (int i = 0; i < json_array.length(); i++) {
Model_Task_List modelobj = new Model_Task_List();
JSONObject json_arrayJSONObject = json_array.getJSONObject(i);
modelobj.setSubject(json_arrayJSONObject.getString("Subject"));
modelobj.setTaskID(json_arrayJSONObject.getInt("TaskID"));
modelobj.setUserName(json_arrayJSONObject.getString("DueDate"));
modelobj.setTaskStatus(json_arrayJSONObject.getString("TaskStatus"));
modelobj.setUserid(json_arrayJSONObject.getString("Owner"));
database_sf_app.insertorUpdate(modelobj);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(), error.toString(), Toast.LENGTH_SHORT).show();
}
});
//Creating request queue
queue.add(jsonObjRequest);
}
//sync operation
//a union b
//a server
//b local storage
//a only - insert local
//b only - send to server
//a = b do nothing
//result
//bind
return view;
}
#Override
public void onResume()
{
super.onResume();
}
#Override
public void onStop() {
super.onStop();
}
}
Here is my TaskAdapter:
import android.content.Context;
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 java.util.List;
public class Task_List_Adapter extends RecyclerView.Adapter<Task_List_Adapter.MyViewHolder> {
private List<Model_Task_List> dataSet;
private Context context;
private static data yog;
Model_Task_List modelTaskList=new Model_Task_List();
public void remove(int position)
{
dataSet.remove(position);
notifyItemRemoved(position);
}
public void edit(int position){
dataSet.set(position, modelTaskList);
notifyItemChanged(position);
}
public void setOnItemClickListener(data listener) {
this.yog = listener;
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
// Model_Task_List Model_Task_List=new Model_Task_List();
TextView textname;
TextView textaddress;
TextView textphnum;
TextView textdegree;
TextView textemail;
ImageView call;
data datas;
public MyViewHolder(final View itemView) {
super(itemView);
this.textname = (TextView) itemView.findViewById(R.id.subject);
this.textaddress = (TextView) itemView.findViewById(R.id.username);
this.textphnum = (TextView) itemView.findViewById(R.id.status);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(yog!=null){
yog.yog(itemView,getLayoutPosition());
}
}
});
// this.imageViewIcon = (ImageView) itemView.findViewById(R.id.imageView);
}
}
public interface data
{
void yog(View v,int position);
}
public Task_List_Adapter(List<Model_Task_List> data,Context context) {
this.dataSet = data;
this.context=context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.task_list_view, parent, false);
MyViewHolder myViewHolder = new MyViewHolder(view);
return myViewHolder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
TextView textViewName = holder.textname;
TextView textViewaddress = holder.textaddress;
TextView textViewphnum = holder.textphnum;
TextView textdegree = holder.textdegree;
TextView textemail=holder.textemail;
textViewName.setText("Subject:"+dataSet.get(position).getSubject());
textViewaddress.setText("DueDate"+dataSet.get(position).getUserName());
textViewphnum.setText("Status:"+dataSet.get(position).getTaskStatus());
}
#Override
public int getItemCount() {
return dataSet.size();
}
}
IS it right way to get id:
taskadapter.setOnItemClickListener(new Task_List_Adapter.data() {
#Override
public void yog(View v, int position) {
Model_Task_List model_task_list=(Model_Task_List)model_task_lists.get(position);
String yog=model_task_list.getSubject().toString();
int yogeshs=model_task_list.getTaskID();
String yogan=Integer.toString(yogeshs);
Toast.makeText(getContext(),yogan,Toast.LENGTH_SHORT).show();
}
});
}
Where i make recyclerview clickable how to get id of sqlite when i click and need to pass the value to next page
The object you are displaying in recyclerview ,
in your case that code must be in TaskAdapter,
put id in that object so when you click on it you will get that object so retrieve ID from that object
clickedObjecj.getId();
defining onClick in the onBindViewHolder is not a good pratice
the correct way is that declare a interface in the adapter class and implement it on the Activity , Using interface we can pass the value
Steps 1:
Decalre Listener for the OnItemClickListener interface
private OnItemClickListener mListener;
Step 2 : declare an interface , this interface will forward our click and data from adapter to our activity
public interface OnItemClickListener {
void onItemClick(int elementId);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
Step 3 : define the on click on ViewHolder and pass the id
//Assigning on click listener on the item and passing the ID value of the item
itemView.setOnClickListener(new View.OnClickListener() { // we can handle the click as like we do in normal
#Override
public void onClick(View v) {
if (mListener != null) {
int elementId = dataSet.get(getAdapterPosition()).getTaskID(); // Get the id of the item on that position
mListener.onItemClick(elementId); // we catch the id on the item view then pass it over the interface and then to our activity
}
}
});
Step 4: implement TaskAdapter.OnItemClickListener in the activity
Step 6: onItemClick method you will recive the value
#Override
public void onItemClick(int itemId) {
Log.d(TAG, "onItemClick: "+String.valueOf(itemId));
}
first you have to set Cursor position into clicked one
Ex: Cursor products <- storing a set of data
to set Cursor to clicked position for example a position value from RecyclerView click event
products.moveToPosition(position);
then use getString as usual
String name = products.getString(products.getColumnIndex("NAME"));
hope it may help
Hmm, my problem just change setOnClickListener to setOnLongClickListener
i declare puplic static int posit in my Adapter
Second in onBindViewHolder of Adapter, i call:
holder.layout_item.setOnLongClickListener(new View.OnLongClickListener() { #Override public boolean online(View view) { posit = arrayList.get(position).getId(); return false; } });
Next, on MainActivity, i want delete 1 object in sqlite
Boolean checkDeleteData = phamTuanVan_sqlite.deleteData(PhamTuanVan_Adapter.posit);
hope it may help

Categories

Resources