I have the following RecyclerView adapter in place. It's working fine to display the items however I want to pass arguments to a Dialog or Fragment when I click one of the items:
public class NovaAdapter extends RecyclerView.Adapter<NovaListRowHolder> {
ArrayList<HashMap<String, String>> novaList = new ArrayList<HashMap<String, String>>();
public static final String STATUS = "status";
public static final String NAME = "name";
public static final String ID = "id";
private Context mContext;
public NovaAdapter(Context context, ArrayList<HashMap<String, String>> novaList) {
this.novaList = novaList;
this.mContext = context;
}
#Override
public NovaListRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.instances_list, null);
NovaListRowHolder mh = new NovaListRowHolder(v);
return mh;
}
#Override
public void onBindViewHolder(NovaListRowHolder novaListRowHolder, int i) {
HashMap<String, String> e = novaList.get(i);
novaListRowHolder.name.setText(e.get(NAME));
novaListRowHolder.status.setText(e.get(STATUS));
novaListRowHolder.setId(e.get(ID));
}
#Override
public int getItemCount() {
return (null != novaList ? novaList.size() : 0);
}class NovaListRowHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
protected TextView name;
protected TextView status;
protected String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public NovaListRowHolder(View view) {
super(view);
view.setOnClickListener(this);
this.name = (TextView) view.findViewById(R.id.nameInstance);
this.status = (TextView) view.findViewById(R.id.statusInstance);
}
public void onClick(View view){
Dialog dialog = new Dialog(view.getContext());
dialog.setContentView(R.layout.instances_listdetail);
dialog.setTitle("Details " + name.getText() + " " + getPosition());
dialog.show();
}
At the moment the click is only opening a placeholder dialog but it isn't passing any data. I tried to search everywhere for examples or tutorials on how to do it but didn't find it anywhere.
Sorry in advance it it's too obvious but it's my first app and I don't have much experience.
You should set the onClickListener in onBindViewHolder to each of the views. You can access the itemView directly from your viewHolder.
Now you can set a tag (or a few) to the view with the click listener, and retrieve them inside your onClick method.
If you need to pass values from recycler view to dialog means then use this
code of onBindViewHolder
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Offers offers = offersList.get(position);
holder.topic.setText(offers.getTopic());
holder.expiry.setText(offers.getExpiry());
}
Simply pass the values of by setText
//TextView inside dialog
offers_dialog_topic = (TextView) dialog.findViewById(R.id.offers_dialog_offer_type);
date_year = (TextView) dialog.findViewById(R.id.date_year);
offers_dialog_topic.setText(topic.getText().toString());
date_year.setText(expiry.getText().toString());
Hope this helps for other.
Thank you.
Related
this is my adapter code
I tried more method, but it's still not working
I don't know where has problem
public class CommentAdapter extends RecyclerView.Adapter<CommentAdapter.CommentViewHolder> {
private Context mContext;
private List<CommentModel> mData;
RequestManager glide;
private LayoutInflater mInflater = null;
private OnItemClickListener mOnItemClickListener = null;
public CommentAdapter(List<CommentModel> mData, Context mContext){
super();
this.mContext = mContext;
this.mData = mData;
this.glide = Glide.with(mContext);
}
#NonNull
#Override
public CommentViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
//View row = LayoutInflater.from(mContext).inflate(R.layout.row_comment,parent,false);
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_comment, parent, false);
CommentViewHolder commentViewHolder = new CommentViewHolder(v);
return commentViewHolder;
}
#Override
public void onBindViewHolder(#NonNull CommentViewHolder holder, final int position) {
final CommentModel commentModel = mData.get(position);
//glide.load(mData.get(position).getUserPhoto()).into(holder.img_user);
Glide.with(mContext).load(mData.get(position).getUserPhoto()).into(holder.img_user);
holder.tv_name.setText(mData.get(position).getUsername());
holder.tv_content.setText(mData.get(position).getComment());
holder.tv_date.setText(mData.get(position).getTime());
}
#Override
public int getItemCount() {
return mData==null ? 0 : mData.size();
//return mData.size();
}
public void addTheCommentData(CommentModel commentModel){
if(commentModel!=null){
mData.add(commentModel);
this.notifyDataSetChanged();
}else {
throw new IllegalArgumentException("No Data!");
}
}
public interface OnItemClickListener {
void onClick(View parent, int position);
}
public class CommentViewHolder extends RecyclerView.ViewHolder{
ImageView img_user;
TextView tv_name,tv_content,tv_date;
public CommentViewHolder(View itemView) {
super(itemView);
img_user = itemView.findViewById(R.id.comment_user_img);
tv_name = itemView.findViewById(R.id.comment_username);
tv_content = itemView.findViewById(R.id.comment_comment);
tv_date = itemView.findViewById(R.id.comment_date);
}
}
}
This is my comment code,
When I type the info and submit, it's will writing my server, but the notifyDataSetChanged is no working.
//This method will parse json data
private void parseData(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
//Creating the newFeedModel object
CommentModel newCommentModel = new CommentModel();
JSONObject json = null;
try {
//Getting json
json = array.getJSONObject(i);
String TAG_CommentID = "CommentID";
String TAG_CommentFID = "CommentFID";
String TAG_CommentUID = "CommentUID";
String TAG_Comment = "Comment";
String TAG_PostUserPhoto = "PostUserPhoto";
String TAG_Username = "Username";
String TAG_Time = "Time";
//String TAG_CommentPhoto = "CommentPhoto";
//Adding data to the newFeedModel object
//Log.d("photo", json.getString(TAG_PostUserPhoto));
newCommentModel.setCommentID(json.getString(TAG_CommentID));
newCommentModel.setFeedID(json.getString(TAG_CommentFID));
newCommentModel.setUserID(json.getString(TAG_CommentUID));
newCommentModel.setComment(json.getString(TAG_Comment));
newCommentModel.setUserPhoto(json.getString(TAG_PostUserPhoto));
newCommentModel.setUsername(json.getString(TAG_Username));
newCommentModel.setTime(json.getString(TAG_Time));
//newCommentModel.setTimestamp(json.getString(TAG_CommentPhoto));
} catch (JSONException e) {
e.printStackTrace();
}
//Adding the newFeedModel object to the list
//listCommentModel.add(newCommentModel);
adapter.addTheCommentData(newCommentModel);
}
//Notifying the adapter that data has been added or changed
this.adapter.notifyDataSetChanged();
//getNewDate();
}
But it cannot be working, I don't know what's happen.
Who can told me where need to modify?
I need to leave activity then go back will display.
First Add ArrayList of CommentModel,
Then Add Your Adapter an pass List via constructor of adapter
CommentAdapter adapter;
ArrayList<CommentModel> list;
Inside Parsing
list = new ArrayList<CommentModel>();
list.add(newCommentModel)
adapter = new CommentAdapter(list,this);
So, I need to add under code in CommentModel.java
public class CommentModel {
private String CommentID;
private String FeedID;
private String UserID;
private String Comment;
private String UserPhoto;
private String Username;
private String Time;
CommentAdapter adapter;
ArrayList<CommentModel> list;
public CommentModel(String nickName, String content, String img) {
this.Username = nickName;
this.Comment = content;
this.UserPhoto = img;
}
public String getTime() {
return Time;
}
public void setTime(String time) {
Time = time;
}
then, this code in activicy
editTextComment = findViewById(R.id.post_detail_comment);
feedid = findViewById(R.id.feedid);
recyclerView = (RecyclerView) findViewById(R.id.rv_comment);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
list = new ArrayList<CommentModel>();
list.add(newCommentModel)
adapter = new CommentAdapter(list,this);
is this right?
In my App I developed a News feature with RecaylerView widget. Now I want to pass CoverImage and Date from this recyclerView to detail page of news. I can pass date of the news successfully. But the cover image is not shown in the detail page. I have found 0 image in my logcat in android monitor window. I cannot not identify what would be the problem here.
My Model class of news is-
public class NewsModel extends RealmObject {
#PrimaryKey
private int image;
private String title;
private String date;
private String detail ;
public NewsModel() {
}
public NewsModel(int image, String title, String date) {
this.image = image;
this.title = title;
this.date = date;
}
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
......
}
My adaper class for news page is
public class NewsAdapter extends
RecyclerView.Adapter<NewsAdapter.NewsHolder> {
private List<NewsModel> newsObject;
private Context context;
public NewsAdapter(Context context, List<NewsModel> newsObject) {
this.context = context;
this.newsObject=newsObject;
}
#Override
public NewsHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.news_row_layout,parent,false);
return new NewsHolder(view);
}
#Override
public void onBindViewHolder(NewsAdapter.NewsHolder holder, int position) {
final NewsModel newsModel=newsObject.get(position);
holder.newsImage.setImageResource(newsModel.getImage());
holder.newsHeadline.setText(newsModel.getTitle());
holder.newsDate.setText(newsModel.getDate());
holder.cardView.setTag(position);
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int pos = (int)view.getTag();
openDetailNews(Integer.toString(newsModel.getImage()),newsModel.getDate());
}
});
}
//open Detail News Page
private void openDetailNews(String...details) {
Intent i=new Intent(context,DetailNews.class);
i.putExtra("image",details[0]);
i.putExtra("date",details[1]);
context.startActivity(i);
}
#Override
public int getItemCount() {
return newsObject.size();
}
public class NewsHolder extends RecyclerView.ViewHolder {
public CardView cardView;
public ImageView newsImage;
public TextView newsHeadline;
public TextView newsDate;
public NewsHolder(View itemView) {
super(itemView);
newsImage=(ImageView)itemView.findViewById(R.id.news_picture);
newsHeadline=(TextView)itemView.findViewById(R.id.news_headline);
newsDate=(TextView) itemView.findViewById(R.id.news_date);
cardView=(CardView)itemView.findViewById(R.id.cardview_news);
}
}
}
The detail news page code where I want to get the cover image and date from news page is-
public class DetailNews extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private List<NewsImageModel> newsObject;
ImageView _coverImage;
TextView _description;
TextView _newsDate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.news_detail);
// Showing and Enabling clicks on the Home/Up button
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
newsObject=getAllImageList();
// setting up views and stuff
setUpUIViews();
Intent intent = getIntent();
//RECEIVE DATA
Log.e("_coverImage",""+_coverImage);
Integer coverImage=intent.getExtras().getInt("image");
Log.e("coverImage",""+coverImage);
String newsDate=intent.getExtras().getString("date");
//BIND DATA
_coverImage.setImageResource(coverImage);
Log.e("coverImage",""+coverImage);
_newsDate.setText(newsDate);
}
private void setUpUIViews() {
_coverImage=(ImageView)findViewById(R.id.news_cover);
_description=(TextView)findViewById(R.id.news_description);
_newsDate=(TextView)findViewById(R.id.news_date);
recyclerView = (RecyclerView)findViewById(R.id.image_list);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(DetailNews.this);
recyclerView.setLayoutManager(layoutManager);
adapter = new NewsDetailAdapter(this,newsObject );
recyclerView.setAdapter(adapter);
}
private List<NewsImageModel> getAllImageList() {
List<NewsImageModel> images = new ArrayList<NewsImageModel>();
......
return images;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
...
}
}
Use this :
public void onClick(View view) {
int pos = (int)view.getTag();
Intent i=new Intent(context,DetailNews.class);
i.putExtra("image",newsModel.getImage());
i.putExtra("date",newsModel.getDate());
context.startActivity(i);
}
and then in your activity:
Intent intent = getIntent();
int imageId = intent.getIntExtra("image",0);
then use this resource id to set your image
_coverImage.setImageResource(imageId);
Try it!
String coverImage=intent.getExtras().getString("image");
int convertCoverImage = Integer.valueOf("coverImage");
_coverImage.setImageResource(convertCoverImage);
You can't directly show a string url or any integer type into a imageview . You need to add Image lib's like Picaso or glide.
follow below steps:
1.Add dependencies:
compile 'com.squareup.picasso:picasso:2.5.2'
2.In your adapter insted of your old code replace with
Picasso.with(context).load(newsModel.getImage()).into(holder.newsImage);
Your problem will be solved.
private int image;
What integer data you are setting for the image? Is it a resource image?
I am trying to show my integers saved in the firebase database in my Recyclerview. I have two Strings I can easily show in my App, but somehow it doesn't work with integers. Even more strange is that when I save a String where before there was an integer I got an error.
Here my database structure
Here I populate my Viewholder
#Override
public void onStart() {
super.onStart();
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<ListItem, ListViewHolder>(
ListItem.class,
R.layout.card_item,
ListViewHolder.class,
mDatabase.orderByChild("minusAccandShare").endAt(0)
) {
#Override
protected void populateViewHolder(ListViewHolder viewHolder, ListItem model, final int position) {
viewHolder.setImage(getActivity().getApplicationContext(), model.getImage());
viewHolder.setHeading(model.getHeading());
viewHolder.setStoreName(model.getStoreName());
viewHolder.setAcceptCount(model.getAcceptCount());
viewHolder.mView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
Intent i = new Intent(getActivity(), DetailActivity.class);
Bundle extras = new Bundle();
extras.putString(EXTRA_QUOTE, firebaseRecyclerAdapter.getRef(position).getKey());
i.putExtra(BUNDLE_EXTRAS, extras);
startActivity(i);
}
});
}
};
recyclerView.setAdapter(firebaseRecyclerAdapter);
}
My ViewHolder
public static class ListViewHolder extends RecyclerView.ViewHolder {
View mView;
public ListViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setImage(Context ctx, String image){
ImageView postImage = (ImageView) mView.findViewById(R.id.im_item_icon);
Picasso.with(ctx).load(image).resize(200,200).into(postImage);
}
public void setHeading(String heading){
TextView card_heading = (TextView) mView.findViewById(R.id.lbl_item_sub_title);
card_heading.setText(heading);
}
public void setStoreName(String storeName){
TextView card_storeName = (TextView) mView.findViewById(R.id.lbl_item_text);
card_storeName.setText(storeName);
}
public void setAcceptCount(String accepts){
TextView accepts_count = (TextView) mView.findViewById(R.id.lbl_accepts_count);
accepts_count.setText(accepts);
}
}
And finally my model
public class ListItem {
private String heading, storeName, image;
private Long accepts;
public ListItem() {
}
public ListItem(String heading,String storeName, Long accepts, String image){
this.heading = heading;
this.storeName = storeName;
this.image = image;
this.accepts = accepts;
}
public String getHeading() {
return heading;
}
public String getStoreName() {
return storeName;
}
public String getImage() {return image;}
public String getAcceptCount() {
return String.valueOf(accepts);
}
In this way I see null where there should stand 200 instead. I tried everything. I even saved an String instead of an integer and tried to show it the same way as the heading String ( which works perfectly) but then I see a blank place... Please help. Thanks
you should create a getter and setter for accepts in ListItem.
public Long getAccepts() {
return accepts;
}
public void setAccepts(Long accepts) {
this.accepts = accepts;
}
I process and setup content which is being delivered as a String which includes http links (http://..) and (can include) normal text (info, mirror, ...).
I am trying to set the normal text as headers in my recylcerview.
This all needs to happen dynamically as I do not know upfront if the String includes normal text and if it is included, how many normal text items there are.
So the recylcerview (could) should look like this:
http://www.link1.com
MIRROR
https://www.link2.com
https://www.link3.com
INFO
http://www.link4.com
http://www.link5.com
Now it looks like this:
MIRROR
http://www.link1.com
http://www.link2.com
http://www.link3.com
According the log it looks ok:
/testpackage.com E/ITEM: https://link1.com
/testpackage.com E/ITEM: MIRROR
/testpackage.com E/ITEM: https://link2.com
/testpackage.com E/ITEM: https://link3.com
I am having trouble getting the headers in the right position in the recyclerview.
I already looked up some solutions and I did read about several possibilities like SectionedRecyclerViewAdapter but I wouldn`t know how to implement it for my needs.
I guess the tricky part of my problem is it needs to be setup dynamically.
My code till now:
SectionViewHolder class:
public class SectionViewHolder extends RecyclerView.ViewHolder {
public TextView name;
public SectionViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.sectionHeader);
}
}
Activity where I setup things:
#EActivity(R.layout.downloads_activity)
public class DownloadsActivity extends BaseActivity {
String outPut;
RecyclerView recyclerView;
AdapterSectionRecycler adapterRecycler;
List<SectionHeader> sectionHeaders;
...
#AfterViews
public void init() {
int i = 0;
List<Child> childList = new ArrayList<>();
sectionHeaders = new ArrayList<>();
//initialize RecyclerView
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
//setLayout Manager
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setHasFixedSize(true);
...
// GET RID OF BAD HTML and SPLIT AS OF <br/>
String html = outPut.replaceAll("<br/></a>", "</a>");
String[] lines = html.split("<br/>");
...
// loop and process URL links and normal text
for (String str : Arrays.asList(lines)) {
Jsoup.parse(str).text();
str.split(",");
// function to parse the URL links and normal text from String
String item = unescapeJavaString(String.valueOf(Html.fromHtml(str)));
if (!str.contains("Use following links")) {
// Add URL links to list
if (item.startsWith("http")) {
childList.add(new Child(item));
}
// Add section headers
if (!item.startsWith("http")) {
sectionHeaders.add(new SectionHeader(childList, item, i));
}
}
Log.i("ITEM", item);
}
adapterRecycler = new AdapterSectionRecycler(this, sectionHeaders);
recyclerView.setAdapter(adapterRecycler);
}
SectionHeader class:
public class SectionHeader implements Section<Child>, Comparable<SectionHeader> {
List<Child> childList;
public String sectionText;
int index;
public SectionHeader(List<Child> childList, String sectionText, int index) {
this.childList = childList;
this.sectionText = sectionText;
this.index = index;
}
#Override
public List<Child> getChildItems() {
return childList;
}
public String getSectionText() {
return sectionText;
}
#Override
public int compareTo(SectionHeader another) {
if (this.index > another.index) {
return -1;
} else {
return 1;
}
}
}
ChildViewHolder:
public class ChildViewHolder extends RecyclerView.ViewHolder {
public TextView name;
public ChildViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.child);
}
}
Child class:
public class Child {
String name;
public Child(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
My AdapterSectionRecycler:
public class AdapterSectionRecycler extends SectionRecyclerViewAdapter<SectionHeader, Child, SectionViewHolder, ChildViewHolder> {
Context context;
public AdapterSectionRecycler(Context context, List<SectionHeader> sectionHeaderItemList) {
super(context, sectionHeaderItemList);
this.context = context;
}
#Override
public SectionViewHolder onCreateSectionViewHolder(ViewGroup sectionViewGroup, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.section_item, sectionViewGroup, false);
return new SectionViewHolder(view);
}
#Override
public ChildViewHolder onCreateChildViewHolder(ViewGroup childViewGroup, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.child, childViewGroup, false);
return new ChildViewHolder(view);
}
#Override
public void onBindSectionViewHolder(SectionViewHolder sectionViewHolder, int sectionPosition, SectionHeader sectionHeader) {
sectionViewHolder.name.setText(sectionHeader.sectionText);
}
#Override
public void onBindChildViewHolder(ChildViewHolder childViewHolder, int sectionPosition, int childPosition, Child child) {
childViewHolder.name.setText(child.getName());
}
}
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