how to auto update RecyclerView.Adapter in android? - android

This is My Code:
public class ItemsListActivity extends AppCompatActivity {
private List<AllItems> listItems;
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_items_list);
Button camera=(Button)findViewById(R.id.camera);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
listItems = new ArrayList<>();
camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(ItemsListActivity.this, Camera.class);
startActivity(i);
}
});
getData();
}
private void getData(){
final ProgressDialog loading = ProgressDialog.show(this,"Loading Data", "Please wait...",false,false);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Config.DATA_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
loading.dismiss();
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
private void parseData(JSONArray array){
for(int i = 0; i<array.length(); i++) {
AllItems items = new AllItems();
JSONObject json = null;
try {
json = array.getJSONObject(i);
items.setImageUrl(json.getString(Config.TAG_IMAGE_URL));
items.setName(json.getString(Config.TAG_NAME));
} catch (JSONException e) {
e.printStackTrace();
}
listItems.add(items);
}
adapter = new CardAdapter(listItems, this);
recyclerView.setAdapter(adapter);
adapter.notifyItemRangeChanged(0, listItems.size());
}
}
And This Is CardAdapter:
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {
private ImageLoader imageLoader;
private Context context;
List<AllItems> superHeroes;
public CardAdapter(List<AllItems> superHeroes, Context context){
super();
this.superHeroes = superHeroes;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.all_items_lists, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
AllItems superHero = superHeroes.get(position);
imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
imageLoader.get(superHero.getImageUrl(), ImageLoader.getImageListener(holder.imageView, R.mipmap.ic_launcher, android.R.drawable.ic_dialog_alert));
holder.imageView.setImageUrl(superHero.getImageUrl(), imageLoader);
holder.textViewName.setText(superHero.getName());
}
#Override
public int getItemCount() {
return superHeroes.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public NetworkImageView imageView;
public TextView textViewName;
public ViewHolder(View itemView) {
super(itemView);
imageView = (NetworkImageView) itemView.findViewById(R.id.imageViewHero);
textViewName = (TextView) itemView.findViewById(R.id.textViewName);
}
}
}
how do I update adapter data in order to display newly received items?

You are creating instance of adapter every time you parsing the data,
just create its instance once in onCreate() method like below:
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
listItems = new ArrayList<>();
adapter = new CardAdapter(listItems, this);
recyclerView.setAdapter(adapter);
and just notify the adapter with your parse data like below:
listItems.add(items);
adapter.notifyDataSetChanged();
will work for you.

Here what is happening that evertime your are calling getData() you are initializing adapter again . Instead you should initialize your adapter in onCreate and in getData just update the list that you are passing in adapter and call adapter.notifyDataSetChanged().
private List<AllItems> listItems;
private RecyclerView recyclerView; private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter; #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_items_list); Button camera=(Button)findViewById(R.id.camera); recyclerView = (RecyclerView) findViewById(R.id.recyclerView); recyclerView.setHasFixedSize(true); layoutManager = new LinearLayoutManager(this); recyclerView.setLayoutManager(layoutManager); listItems = new ArrayList<>();
adapter = new CardAdapter(listItems, this);
recyclerView.setAdapter(adapter);
camera.setOnClickListener(new View.OnClickListener() { #Override public void onClick(View view) { Intent i = new Intent(ItemsListActivity.this, Camera.class); startActivity(i); } }); getData(); }
private void getData(){
final ProgressDialog loading = ProgressDialog.show(this,"Loading Data", "Please wait...",false,false);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Config.DATA_URL, new Response.Listener<JSONArray>() { #Override public void onResponse(JSONArray response) { loading.dismiss(); parseData(response); }
}, new Response.ErrorListener() {
#Override public void onErrorResponse(VolleyError error) { } }); RequestQueue requestQueue = Volley.newRequestQueue(this); requestQueue.add(jsonArrayRequest); }
private void parseData(JSONArray array){
for(int i = 0; i<array.length(); i++) {
AllItems items = new AllItems(); JSONObject json = null;
try
{
json = array.getJSONObject(i); items.setImageUrl(json.getString(Config.TAG_IMAGE_URL)); items.setName(json.getString(Config.TAG_NAME)); } catch (JSONException e) { e.printStackTrace(); } listItems.add(items); }
}
adapter.notifyDataSetChanged().
}
And if you don't want to show previous items call lisItems.clear() before adding new items

Related

Error with RecyclerView: No adapter attached; skipping layout

I can't get my code work
I'm trying to get a list of my database activities.
A lot of research here and none of the answers helped me
My Adapter
public class AtividadesAdapter extends RecyclerView.Adapter<AtividadesAdapter.AtividadesViewHolder> {
private Context mCtx;
private List<Atividades> atividadesList;
public AtividadesAdapter(Context mCtx, List<Atividades> atividadesList) {
this.mCtx = mCtx;
this.atividadesList = atividadesList;
}
#Override
public AtividadesViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.atividades_lista, null);
return new AtividadesViewHolder(view);
}
#Override
public void onBindViewHolder(AtividadesViewHolder holder, int position) {
Atividades atividades = atividadesList.get(position);
holder.textViewAtividade.setText(atividades.getAtividade());
holder.textViewData.setText(String.valueOf(atividades.getDataPrevista()));
holder.textViewHora.setText(String.valueOf(atividades.getHora()));
holder.textViewDestinatarios.setText(atividades.getDestinatarios());
}
#Override
public int getItemCount() {
return atividadesList.size();
}
class AtividadesViewHolder extends RecyclerView.ViewHolder {
TextView textViewAtividade, textViewData, textViewHora, textViewDestinatarios;
public AtividadesViewHolder(View itemView) {
super(itemView);
textViewAtividade = itemView.findViewById(R.id.textViewAtividade);
textViewData = itemView.findViewById(R.id.textViewData);
textViewHora = itemView.findViewById(R.id.textViewHora);
textViewDestinatarios = itemView.findViewById(R.id.textViewDestinatarios);
}
}
}
My activity
public class AtividadesActivity extends AppCompatActivity {
private static final String URL_ATIVIDADES = "";
List<Atividades> atividadesList = new ArrayList<>();
public RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.atividadesrecyclerview);
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
loadAtividades();
}
private void loadAtividades() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_ATIVIDADES,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
JSONObject a = array.getJSONObject(i);
Log.d("Valores", a.getString("Atividade"));
atividadesList.add(new Atividades(
a.getInt("idAtividade"),
a.getString("Atividade"),
java.sql.Date.valueOf(a.getString("dataPrevista")),
java.sql.Time.valueOf(a.getString("hora")),
a.getString("Destinatarios"),
a.getString("Local")
));
}
AtividadesAdapter mAdapter = new AtividadesAdapter(AtividadesActivity.this, atividadesList);
recyclerView.setAdapter(mAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
Volley.newRequestQueue(this).add(stringRequest);
}
}
Everytime i'm trying to start the app, i get this error.
I have already change the xml files to match with the examples provided here but still have no success.
Please attach parent and the rest:
#Override
public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
return new AtividadesViewHolder(LayoutInflater.from(mCtx).inflate(R.layout.atividades_lista, parent, false));
}
Based on your question and the code I think this will help you.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.atividadesrecyclerview);
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
AtividadesAdapter mAdapter = new AtividadesAdapter(getApplicationContext, atividadesList);
recyclerView.setAdapter(mAdapter);
loadAtividades();
}
Add to your adapter:
public AtividadesAdapter(Context mCtx) {
this.mCtx = mCtx;
}
public void setItems(#NonNull final List<Atividades> items) {
if (atividadesList != null) {
atividadesList.clear();
} else {
atividadesList = new ArrayList<>();
}
atividadesList.addAll(items);
}
onCreate of the activity should be as follows:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.atividadesrecyclerview);
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
mAdapter = new AtividadesAdapter(AtividadesActivity.this);
recyclerView.setAdapter(mAdapter);
loadAtividades();
}
In loadAtividades() call to setItems:
mAdapter.setItems(atividadesList);

Getting empty RecyclerVew item sometimes despite calling adapterlist.clear()

I'm trying to show the details of students in a recyclerview, obtained from a web service. The app works in a way that in an Activity, it opens list of students and then on touch of a student, it opens another activity which will show the details of that particular student in a recyclerview.
Problem:
I sometimes get an empty recyclerview item either above or below the valid item with data. I tried calling StuDetailsDataAdapterClassList.clear(); but it doesn't fix the issue. Some times it works fine but I don't understand why it is happening. Your help is valuable for me.
public class StudentDetailsActivity extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView recyclerView2;
RecyclerView.Adapter recyclerViewAdapter;
RecyclerView.Adapter recyclerViewAdapter2;
LinearLayoutManager recyclerViewlayoutManager;
RequestQueue requestQueue ;
RequestQueue requestQueue2 ;
List<StudentDataModel> StuDetailsDataAdapterClassList;
String stuIDForParse;
StudentDataModel GetStuDataModel = new StudentDataModel();
.....
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_personnel_details);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
collapsingToolbarLayout = (SubtitleCollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView4);
recyclerView2 =(RecyclerView)findViewById(R.id.recyclerView5);
recyclerViewlayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(recyclerViewlayoutManager);
StuDetailsDataAdapterClassList=new ArrayList<>();
LinearLayoutManager layoutManager
= new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
recyclerView2.setLayoutManager(layoutManager);
//I have a horizontal recyclerview below the vertical recyclerview. This is the layout manager for that recyclerview.
recyclerView2.setNestedScrollingEnabled(false);
//Set collapse & expanded title color
collapsingToolbarLayout.setExpandedSubtitleTextColor(getResources().getColor(R.color.divider));
setSupportActionBar(toolbar);
//Enable back button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
....
//clearing list
StuDetailsDataAdapterClassList.clear();
PIC__WEB_CALL();
STU_WEB_CALL();
}
public void STU_WEB_CALL(){
String HTTP_SERVER_URL= String.format("http://www.student.com/%1$s",stuIDForParse);
JsonArrayRequest jsArrRequest = new JsonArrayRequest
(Request.Method.GET, HTTP_SERVER_URL, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
RES_PER_PARSE_DATA_AFTER_WEBCALL(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
}
}){
};
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsArrRequest);
}
public void RES_PER_PARSE_DATA_AFTER_WEBCALL(JSONArray array){
for(int i = 0; i<array.length(); i++) {
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetStuDataModel.setDob(json.getString("Date_Of_Birth"));
GetStuDataModel.setStuName(json.getString("Name"));
GetStuDataModel.setGradeName(json.getString("Grade"));
//Set the title on collapsing toolbar
collapsingToolbarLayout.setTitle(GetStuDataModel.getFullName());
} catch (JSONException e) {
e.printStackTrace();
}
}
if (array.length() != 0) {
StuDetailsDataAdapterClassList.add(GetStuDataModel);
collapsingToolbarLayout.setSubtitle(GetStuDataModel.getPerTitle());
recyclerViewAdapter = new StudentDetailsAdapter(StuDetailsDataAdapterClassList, this);
recyclerView.setAdapter(recyclerViewAdapter);
}
}
public void Horizontal_RecyclerView_WEB_CALL(){
//....more code
}
adapter
public class StudentDetailsAdapter extends RecyclerView.Adapter<StudentDetailsAdapter.ViewHolder> {
Context context;
public List<StudentDataModel> dataModels;
public StudentDetailsAdapter(List<StudentDataModel> getDataAdapter, Context context){
super();
Log.i("LPLP","I'm here");
this.dataModels = getDataAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.student_details_card, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(final StudentDetailsAdapter.ViewHolder viewHolder, final int position) {
final StudentDataModel dataAdapter = dataModels.get(position);
viewHolder.grade.setText(dataAdapter.getGradeName());
viewHolder.stuName.setText(dataAdapter.getStuName());
viewHolder.dob.setText(dataAdapter.getDob());
}
#Override
public int getItemCount() {
return dataModels.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public TextView grade;
public TextView stuName;
public TextView dob;
ConstraintLayout constraintLayout;
public ViewHolder(View itemView) {
super(itemView);
grade=(TextView)itemView.findViewById(R.id.textViewGrade);
stuName=(TextView)itemView.findViewById(R.id.textViewStuName);
dob=(TextView)itemView.findViewById(R.id.textViewDOB)
constraintLayout=(ConstraintLayout)itemView.findViewById(R.id.constrainLayout);
}
}
}

android - recyclerview cannot click and get position

I have tried some code to can click recyclerview item and get position, but I can't click the recyclerview item.. the data I get from url. So I wan't switch activity with get the item user click..
how I can fix that?
this code for adapter
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
Context context;
private static final String TAG = RecyclerViewAdapter.class.getSimpleName();
List<GetDataAdapter> getDataAdapter;
ImageLoader imageLoader1;
public RecyclerViewAdapter(List<GetDataAdapter> getDataAdapter, Context context) {
super();
this.getDataAdapter = getDataAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_items, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder Viewholder, int position) {
GetDataAdapter getDataAdapter1 = getDataAdapter.get(position);
imageLoader1 = ServerImageParseAdapter.getInstance(context).getImageLoader();
imageLoader1.get(getDataAdapter1.getImageServerUrl(),
ImageLoader.getImageListener(
Viewholder.networkImageView,//Server Image
R.mipmap.ic_launcher,//Before loading server image the default showing image.
android.R.drawable.ic_dialog_alert //Error image if requested image dose not found on server.
)
);
Viewholder.networkImageView.setImageUrl(getDataAdapter1.getImageServerUrl(), imageLoader1);
Viewholder.ImageTitleNameView.setText(getDataAdapter1.getImageTitleName());
}
#Override
public int getItemCount() {
return getDataAdapter.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public TextView ImageTitleNameView;
public NetworkImageView networkImageView;
public ViewHolder(View itemView) {
super(itemView);
ImageTitleNameView = (TextView) itemView.findViewById(R.id.textView_item);
networkImageView = (NetworkImageView) itemView.findViewById(R.id.VollyNetworkImageView1);
}
}
}
and this code for mainactivity
public class MainActivity extends AppCompatActivity {
List<GetDataAdapter> GetDataAdapter1;
RecyclerView recyclerView;
RecyclerView.LayoutManager recyclerViewlayoutManager;
RecyclerView.Adapter recyclerViewadapter;
String GET_JSON_DATA_HTTP_URL = "http://androidblog.esy.es/ImageJsonData.php";
String JSON_IMAGE_TITLE_NAME = "image_title";
String JSON_IMAGE_URL = "image_url";
JsonArrayRequest jsonArrayRequest ;
RequestQueue requestQueue ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GetDataAdapter1 = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerview1);
recyclerView.setHasFixedSize(true);
recyclerViewlayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(recyclerViewlayoutManager);
JSON_DATA_WEB_CALL();
}
public void JSON_DATA_WEB_CALL(){
jsonArrayRequest = new JsonArrayRequest(GET_JSON_DATA_HTTP_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array){
for(int i = 0; i<array.length(); i++) {
GetDataAdapter GetDataAdapter2 = new GetDataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setImageTitleNamee(json.getString(JSON_IMAGE_TITLE_NAME));
GetDataAdapter2.setImageServerUrl(json.getString(JSON_IMAGE_URL));
} catch (JSONException e) {
e.printStackTrace();
}
GetDataAdapter1.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1, this);
recyclerView.setAdapter(recyclerViewadapter);
}
}
getdataadapter
public class GetDataAdapter {
public String ImageServerUrl;
public String ImageTitleName;
public String getImageServerUrl() {
return ImageServerUrl;
}
public void setImageServerUrl(String imageServerUrl) {
this.ImageServerUrl = imageServerUrl;
}
public String getImageTitleName() {
return ImageTitleName;
}
public void setImageTitleNamee(String Imagetitlename) {
this.ImageTitleName = Imagetitlename;
}
}
You need to set onClickListener to your item view. You can do by following below steps:
Set onCLickListener to root view of your list item.
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_items, parent, false);
Add below code in onCreateViewHolder:
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Add your logic here
}
});
You can add listener while onBindViewHolder:
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Add your logic here
}
});
Thanks.
Put a listener on your recycler item view and then in onclick, start intent to open new activity. Pass the data object you want to pass with the intent.
//make sure your model class GetDataAdapter implements Parcelable
holder.itemView.setOnclickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(this, ActivityToOpen.class);
intent.putExtra("key",Your Object to pass);// getDataAdapter1 in your case
context.startActivity(intent);
}
});
then in your Startted activity receive your object like this
YourObject obj = getIntent().getParcelableExtra("key");
//Your case
GetDataAdapter obj = getIntent().getParcelableExtra("key");

Android Recycler View

I am using RecyclerView to display my products, problem is when if I select the first products and scroll down to the end of list I see different products selected and when i scroll back to top of list the first item is not selected.
My Adapter
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder> {
String u = "http://192.185.52.231/~sabby070/hyype/";
Context context1;
private java.util.List<ProductDetails> List;
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_list, parent, false);
return new MyViewHolder(itemView);
}
public RecyclerAdapter(List<ProductDetails> DataList, FragmentActivity activity) {
this.List = DataList;
context1 = activity;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView Likecount;
public ImageView Image;
public ImageView Imagelike, ImageUnlike;
public MyViewHolder(View view) {
super(view);
Likecount = (TextView) view.findViewById(R.id.textView_itemPrice);
Image = (ImageView) view.findViewById(R.id.imageView_imgtosold);
Imagelike = (ImageView)view.findViewById(R.id.Like_Button);
ImageUnlike = (ImageView)view.findViewById(R.id.UnLike_Button);
}
}
#Override
public void onBindViewHolder(final RecyclerAdapter.MyViewHolder holder, final int position) {
final ProductDetails detail = List.get(position);
holder.Likecount.setText(detail.getLikeCount());
Glide.with(context1).load(u+detail.getImage()).override(600, 200).diskCacheStrategy(DiskCacheStrategy.ALL).into(holder.Image);
holder.Image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context1, ""+position, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context1, Buy_Product.class);
intent.putExtra("Product Name",detail.getLikeCount());
intent.putExtra("Product Image",detail.getImage());
context1.startActivity(intent);
}
});
holder.Imagelike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holder.Imagelike.getVisibility()==View.VISIBLE)
{
holder.Imagelike.setVisibility(View.GONE);
holder.ImageUnlike.setVisibility(View.VISIBLE);
}
}
});
holder.ImageUnlike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holder.ImageUnlike.getVisibility()==View.VISIBLE)
{
holder.Imagelike.setVisibility(View.VISIBLE);
holder.ImageUnlike.setVisibility(View.GONE);
}
}
});
}
#Override
public int getItemCount() {
return List.size();
}
}
My class
public class Men_Fragment extends Fragment {
static String URL = "http://192.185.52.231/~sabby070/hyype/index.php?action=timeline&user_id=53&post_category=timeline";
private List<ProductDetails> DataList = new ArrayList<>();
private RecyclerView recyclerView;
private RecyclerAdapter rAdapter;
String img;
String a;
Boolean list[];
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_men_, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.men_recycler_view);
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(response);
for (int i = 0; i < response.length(); i++) {
JSONObject obj = jsonObject.getJSONObject(String.valueOf(i));
a = obj.getString("like_count");
img = obj.getString("video_thumb");
final ProductDetails details = new ProductDetails(a, img);
DataList.add(details);
rAdapter = new RecyclerAdapter(DataList, getActivity());
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 2);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(rAdapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "" + error, Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
return view;
}
}
You have to take List(with boolean) and store selected values in that list and then use those values in onBindView()
In your ProductDetails class add a field boolean selected;
In your onClick() add List.get(position).setSelected(!List.get(position).isSelected()); to check/uncheck as needed.
Finaly in your onBindViewHolder(...) add
if(List.get(position).isSelected()){
holder.Imagelike.setVisibility(View.VISIBLE);
}else{
holder.ImageUnlike.setVisibility(View.GONE);
}

Recyclerview not display vediothumbnail

i am working and i want to display a video in recyclerview from server its geting data not displaying video thumbnail its showing only text and displaing error thumbnail i dont know where i am wrong please review my code and tell me where i am wrong ,
myActivity
public class TestingActivity extends AppCompatActivity {
private List<TestingModel> listiIems;
//Creating Views
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.testingactivity);
//Initializing Views
recyclerView = (RecyclerView) findViewById(R.id.recyclerView_test);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
listiIems = new ArrayList<>();
//Calling method to get data
getData();
}
//This method will get data from the web api
private void getData() {
String Data_Url="http://www.example.com/vedio.json";
//Showing a progress dialog
final ProgressDialog loading = ProgressDialog.show(this, "Loading Data", "Please wait...", false, false);
//Creating a json array request
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Data_Url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Dismissing progress dialog
loading.dismiss();
//calling method to parse json array
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(jsonArrayRequest);
}
//This method will parse json data
private void parseData(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
TestingModel item = new TestingModel();
JSONObject json = null;
try {
json = array.getJSONObject(i);
item.setUrl_image(json.getString("audio"));
item.setTest_name(json.getString("txt"));
} catch (JSONException e) {
e.printStackTrace();
}
listiIems.add(item);
}
//Finally initializing our adapter
adapter = new TestingAdapter(listiIems, this);
//Adding adapter to recyclerview
recyclerView.setAdapter(adapter);
}
}
Model
public class TestingModel {
public String getUrl_image() {
return url_image;
}
public void setUrl_image(String url_image) {
this.url_image = url_image;
}
public String getTest_name() {
return test_name;
}
public void setTest_name(String test_name) {
this.test_name = test_name;
}
private String url_image;
private String test_name;
}
Adapter
public class TestingAdapter extends RecyclerView.Adapter<TestingAdapter.ViewHolder> {
private ImageLoader imageLoader;
private Context context;
String url;
//List of superHeroes
List<TestingModel> listItems;
public TestingAdapter(List<TestingModel> listItems, Context context) {
super();
//Getting all the superheroes
this.listItems = listItems;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.testing_list, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
TestingModel items = listItems.get(position);
imageLoader = CustomVolleyRequest1.getInstance(context).getImageLoader();
imageLoader.get(items.getUrl_image(), ImageLoader.getImageListener(holder.imageView, R.drawable.placeholder, android.R.drawable.ic_dialog_alert));
holder.imageView.setImageUrl(items.getUrl_image(), imageLoader);
holder.textViewName.setText(items.getTest_name());
holder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
url = listItems.get(position).getUrl_image();
Log.e("urlis","==>"+url);
}
});
}
#Override
public int getItemCount() {
return listItems.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public NetworkImageView imageView;
public TextView textViewName;
public ViewHolder(View itemView) {
super(itemView);
imageView = (NetworkImageView) itemView.findViewById(R.id.testingimage);
textViewName = (TextView) itemView.findViewById(R.id.texting_text);
}
}
}
help me
First of all, Check in adapter. Are you getting url is image or video. If url is contain image then need to check in ImageLoader Library. you can better use with glide and picasso.
Its very easy to use picasso. You can found picasso from this link
http://square.github.io/picasso/
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
If your url contain video then you have to create thumbnail from url using Thumnail Util
Bitmap thumb = ThumbnailUtils.createVideoThumbnail(filePath,
Thumbnails.MINI_KIND); imageview.setBitmapImage(thumb);

Categories

Resources