Getting same item position in RecyclerView, when click on back button - android

I have implemented one app where I am using RecyclerView in fragments. There are 3 buttons, 1 image and some text on every item. If I scroll and click on "View Profile" button then new activity will open which is running successfully but when I call back button then the Item is coming on start position. I need item will come at the same position.
Item Image
Code for Fragment
public class Broader_Match_Tab extends Fragment{
int lastVisibleItemPosition;
SessionManager session;
private List<SuperHero> listSuperHeroes;
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
public ProgressBar progressBar;
private RequestQueue requestQueue;
private int requestCount1 = 1;
private Boolean isStarted = false;
private Boolean isVisible = false;
boolean isLastPageLoaded = false;
public String email;
TextView tvMSG;
public Broader_Match_Tab() {}
#Override
public void onStart() {
super.onStart();
isStarted = true;
if (isVisible && isStarted){
getData();
}
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
isVisible = isVisibleToUser;
if (isStarted && isVisible && (! isLastPageLoaded)) { getData(); } }
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.activity_main_test, container, false);
session = new SessionManager(getActivity());
// get user data from session
HashMap<String, String> user = session.getUserDetails();
email = user.get(SessionManager.KEY_EMAIL);
return view;
}
public void onViewCreated(View v, Bundle savedInstanceState) {
super.onViewCreated(v, savedInstanceState);
recyclerView = (RecyclerView) v.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
listSuperHeroes = new ArrayList<>();
requestQueue = Volley.newRequestQueue(getContext());
adapter = new CardAdapter(listSuperHeroes, getActivity());
recyclerView.setAdapter(adapter);
progressBar = (ProgressBar) v.findViewById(R.id.progressBar1);
tvMSG = (TextView)v.findViewById(R.id.tvMSG);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int
newState) {
super.onScrollStateChanged(recyclerView, newState);
if (isLastItemDisplaying(recyclerView)) {
getData();
}
}
});
}
private JsonArrayRequest getDataFromServer(int requestCount) {
final String DATA_URL = "https://www.example.com";
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(DATA_URL + String.valueOf(requestCount),
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
if (response.length() == 0) {
progressBar.setVisibility(View.GONE);
tvMSG.setText("There is no broader matches");
isLastPageLoaded = true;
}
else {
parseData(response);
tvMSG.setVisibility(View.GONE);
progressBar.setVisibility(View.GONE);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressBar.setVisibility(View.GONE);
Toast.makeText(getActivity(), "No More Items Available", Toast.LENGTH_SHORT).show();
}
});
return jsonArrayRequest;
}
private void getData() {
if(!isLastPageLoaded){
requestQueue.add(getDataFromServer(requestCount1));
requestCount1++;
}}
private void parseData(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
SuperHero superHero = new SuperHero();
JSONObject json = null;
try {
json = array.getJSONObject(i);
superHero.setImageUrl(json.getString(Config_Test.TAG_IMAGE_URL));
superHero.setMglId(json.getString(Config_Test.TAG_MGLID));
superHero.setAge(json.getString(Config_Test.TAG_AGE));
superHero.setAgeHeight(json.getString(Config_Test.TAG_AGEHEIGHT));
superHero.setCommunity(json.getString(Config_Test.TAG_COMMUNITY));
superHero.setCaste(json.getString(Config_Test.TAG_CASTE));
superHero.setOccupation(json.getString(Config_Test.TAG_OCCUPATION));
superHero.setIncome(json.getString(Config_Test.TAG_INCOME));
superHero.setShortlist(json.getString(Config_Test.TAG_SHORTLIST));
superHero.setExpress_Intrest(json.getString(Config_Test.TAG_EXPRESSINTREST));
} catch (JSONException e) {
e.printStackTrace();
}
listSuperHeroes.add(superHero);
}
adapter.notifyDataSetChanged();
}
private boolean isLastItemDisplaying(RecyclerView recyclerView) {
if (recyclerView.getAdapter().getItemCount() != 0) {
lastVisibleItemPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastCompletelyVisibleItemPosition();
if (lastVisibleItemPosition != RecyclerView.NO_POSITION && lastVisibleItemPosition == recyclerView.getAdapter().getItemCount() - 1)
return true;
}
return false;
}
}
Adapter Code
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder>
{
private static final String url ="https://www.example.com";
private static final String url1 = "https://www.example.com";
private static final String KEY_MATRI_ID_TO="matriID_to";
private static final String KEY_MATRI_ID_BY="matriID_by";
SessionManager session;
public String matri_id_to, matri_id_by, str_gender;
String str_shortlist,str_EI;
//Imageloader to load image
private ImageLoader imageLoader;
private Context context;
//List to store all superheroes
List<SuperHero> superHeroes;
//Constructor of this class
public CardAdapter(List<SuperHero> superHeroes, Context context){
super();
//Getting all superheroes
this.superHeroes = superHeroes;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.superheroes_list, parent, false);
// Session class instance
session = new SessionManager(context);
session.checkLogin();
// get user data from session
HashMap<String, String> user = session.getUserDetails();
matri_id_by = user.get(SessionManager.KEY_EMAIL);
str_gender = user.get(SessionManager.KEY_GENDER);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
//Getting the particular item from the list
final SuperHero superHero = superHeroes.get(position);
//Loading image from url
imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
if(str_gender.equalsIgnoreCase("Male")) {
imageLoader.get(superHero.getImageUrl(), ImageLoader.getImageListener(holder.imageView, R.drawable.image, R.drawable.girl));
}
else {
imageLoader.get(superHero.getImageUrl(), ImageLoader.getImageListener(holder.imageView, R.drawable.image, R.drawable.boy));
}
int pos = getItemViewType(position);
if(superHeroes.get(pos).getImageUrl() == null) {
holder.imageView.setVisibility(View.GONE);
} else {
holder.imageView.setImageUrl(superHero.getImageUrl(), imageLoader);
}
holder.textViewId.setText(superHero.getMglId());
holder.AgeHeight.setText(superHero.getAgeHeight()+" / "+superHero.getAge());
holder.Community.setText(superHero.getCommunity()+" / "+superHero.getCaste());
holder.Occupation.setText(superHero.getOccupation());
holder.Income.setText(superHero.getIncome());
str_shortlist = superHero.getShortlist();
if(str_shortlist.toString().equalsIgnoreCase("Shortlisted")) {
holder.btnShortlist.setText(str_shortlist);
holder.btnShortlist.setBackgroundColor(Color.parseColor("#FF0E3671"));
holder.btnShortlist.setEnabled(false);
}
else{
holder.btnShortlist.setEnabled(true);
holder.btnShortlist.setText(str_shortlist);
holder.btnShortlist.setBackgroundColor(Color.parseColor("#2a7fff"));
}
str_EI = superHero.getExpress_Intrest();
Log.e("str_EI_____",str_EI);
if(str_EI.toString().equalsIgnoreCase("Accepted")) {
holder.btnEI.setText(str_EI);
holder.btnEI.setBackgroundColor(Color.parseColor("#FF045B49"));
holder.btnEI.setEnabled(false);
}
else if(str_EI.toString().equalsIgnoreCase("Reject")){
holder.btnEI.setText(str_EI);
holder.btnEI.setBackgroundColor(Color.parseColor("#FF045B49"));
holder.btnEI.setEnabled(false);
}
else if(str_EI.toString().equalsIgnoreCase("Declined")){
holder.btnEI.setText(str_EI);
holder.btnEI.setBackgroundColor(Color.parseColor("#FF045B49"));
holder.btnEI.setEnabled(false);
}
else if(str_EI.toString().equalsIgnoreCase("Pending..")){
holder.btnEI.setText(str_EI);
holder.btnEI.setBackgroundColor(Color.parseColor("#FF045B49"));
holder.btnEI.setEnabled(false);
}
else
{
holder.btnEI.setEnabled(true);
holder.btnEI.setText(str_EI);
holder.btnEI.setBackgroundColor(Color.parseColor("#00aa88"));
}
holder.btnShortlist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
superHero.setShortlist("Wait...");
holder.btnShortlist.setText(superHero.getShortlist());
matri_id_to = superHero.getMglId();
holder.shortlist(position);
}
});
holder.btnViewProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent n = new Intent(holder.itemView.getContext(),BlankActivity.class);
String str_id = holder.textViewId.getText().toString();
n.putExtra("ID",str_id);
holder.itemView.getContext().startActivity(n);
}
});
holder.btnEI.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
superHero.setExpress_Intrest("Wait...");
holder.btnEI.setText(superHero.getExpress_Intrest());
matri_id_to = superHero.getMglId();
holder.expressInterest(position);
}
});
}
public SuperHero getItem(int position){
return superHeroes.get(position);
}
#Override
public int getItemCount() {return superHeroes.size();}
#Override
public int getItemViewType(int position) {
return position;
}
class ViewHolder extends RecyclerView.ViewHolder{
public NetworkImageView imageView;
public TextView textViewId;
public TextView AgeHeight;
public TextView Community;
public TextView Occupation;
public TextView Income;
public Button btnShortlist;
public Button btnViewProfile;
public Button btnEI;
//Initializing Views
public ViewHolder(final View itemView) {
super(itemView);
imageView = (NetworkImageView) itemView.findViewById(R.id.imageViewHero);
textViewId = (TextView) itemView.findViewById(R.id.textViewId);
AgeHeight = (TextView) itemView.findViewById(R.id.AgeHeight);
Community = (TextView) itemView.findViewById(R.id.Community);
Occupation = (TextView) itemView.findViewById(R.id.Occupation);
Income = (TextView) itemView.findViewById(R.id.Income);
btnShortlist = (Button) itemView.findViewById(R.id.btnshort);
btnViewProfile = (Button) itemView.findViewById(R.id.buttonViewProfile);
btnEI = (Button) itemView.findViewById(R.id.btnExpressIntrest);
}
public void shortlist(final int position) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.trim().equalsIgnoreCase("success")) {
superHeroes.get(position).setShortlist("Shortlisted");
// holder.btnShortlist.setText(superHero.getShortlist());
notifyDataSetChanged();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put(KEY_MATRI_ID_BY, matri_id_by);
params.put(KEY_MATRI_ID_TO, matri_id_to);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(stringRequest);
}
public void expressInterest(final int position) {
StringRequest stringRequest1 = new StringRequest(Request.Method.POST, url1, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(response.trim().equalsIgnoreCase("success")) {
superHeroes.get(position).setExpress_Intrest("Pending..");
notifyDataSetChanged();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put(KEY_MATRI_ID_BY,matri_id_by);
params.put(KEY_MATRI_ID_TO,matri_id_to);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(stringRequest1);
}
}
}

Save Instance Code:
Parcelable mListState;
protected void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(state);
// Save list state
mListState = mLayoutManager.onSaveInstanceState();
state.putParcelable(LIST_STATE_KEY, mListState);
}
Restore State Code:
protected void onRestoreInstanceState(Bundle state) {
super.onRestoreInstanceState(state);
// Retrieve list state and list/item positions
if(state != null)
mListState = state.getParcelable(LIST_STATE_KEY);
}
Here in onResume() update the layout manager:
#Override
protected void onResume() {
super.onResume();
if (mListState != null) {
mLayoutManager.onRestoreInstanceState(mListState);
}
}
Hope this helps

The main problem is that onPause you are clearing the whole data and when the fragment getting visible again you are requesting to server from the page 1. Comment the following code.
#Override
public void onPause(){
super.onPause();
//listSuperHeroes.clear();
//adapter.notifyDataSetChanged();
//requestCount1=1;
}
}
update the isLastPageLoaded here:
private boolean isLastPageUpdated = false;
private JsonArrayRequest getDataFromServer(int requestCount) {
final String DATA_URL = "https://www.XYZ.php?matri_id="+email+"&page=";
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(DATA_URL + String.valueOf(requestCount),
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
if (response.length() == 0) {
progressBar.setVisibility(View.GONE);
tvMSG.setText("There is no broader matches");
isLastPageLoaded = true;
}
else {
parseData(response);
tvMSG.setVisibility(View.GONE);
progressBar.setVisibility(View.GONE);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressBar.setVisibility(View.GONE);
Toast.makeText(getActivity(), "No More Items
Available", Toast.LENGTH_SHORT).show();
}
});
return jsonArrayRequest;
}
and in getData()
private void getData() {
if(!isLastPageUpdated){
requestQueue.add(getDataFromServer(requestCount1));
requestCount1++;
}}

save the position of adapter in some variable in adapter. change scroll to that position on back pressed using
linearLayoutManager.scrollToPositionWithOffset(int, int);
inside activity.

You need to override onBackPressed() and add recyclerView.scrollToPosition(position);
#Override
public void onBackPressed() {
super.onBackPressed();
recyclerView.scrollToPosition(position);
finish();
}

save the position of item clicked in onSaveInstanceState and pass that to scrollToPosition or
try below
private static final String SELECTED_KEY = "selected_position";
#Override
public void onSaveInstanceState(Bundle outState) {
lastFirstVisiblePosition = ((LinearLayoutManager)mRecylerView.getLayoutManager()).findFirstCompletelyVisibleItemPosition();
outState.putInt(SELECTED_KEY, lastFirstVisiblePosition);
}
in Oncreate
Edited..
if(savedInstanceState != null && savedInstanceState.containsKey(SELECTED_KEY))
{
lastFirstVisiblePosition = savedInstanceState.getInt(SELECTED_KEY);
}
use
((LinearLayoutManager) mRecylerView.getLayoutManager()).scrollToPosition(lastFirstVisiblePosition) or
mRecylerView.smoothScrollToPosition(lastFirstVisiblePosition);
after data is populated, preferably after adapter.notifyDataSetChanged();

I was experiencing the same issue before, then I solved my problem with a simpler solution. I just called adapter.startListening(); in onViewCreated() instead of onStart and called adapter.stopListening(); in onDestroyView() instead of onStop().
That prevented the entire list from regenerating while coming back from next activity and thus retained the scroll position where it was previously.

I've solved the problem as follow:
Called .startListening in both onViewCreated and in onStart
Called .stopListening in onDestroyView
Don't call .stopListening in onStop
My code in the fragment as follow:
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle
savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (mAdapterHb != null) {
mAdapterHb.startListening();
}
}
#Override
public void onStart() {
super.onStart();
if (mAdapterHb != null) {
mAdapterHb.startListening();
}
}
#Override
public void onStop() {
super.onStop();
// if (mAdapterHb != null) {
// mAdapterHb.stopListening();
// }
}
#Override
public void onDestroyView() {
super.onDestroyView();
if (mAdapterHb != null) {
mAdapterHb.stopListening();
}
}

Related

RecyclerView not updating after input

Im saving data in MySql and want to add an update function to my saved notes. Im displaying the arraylist of notes in a recyclerview. When updating i have implemented a click function on my cardview where it passes intent to the Update activity. I have a problem when updating a single row of the note. Please help!
I have tried to Implement the method adapter.notifyDataSetChanged in my main Activity but its not still updating the recyclerview.
Main Adapter.java
public class MainAdapter extends RecyclerView.Adapter<MainAdapter.CustomViewHoler>{
private Context context;
private ArrayList<Note> noter;
private ItemClickListener itemClickListener;
private int INTENT_EDIT = 200;
class CustomViewHoler extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView tv_title, tv_note, tv_date;
CardView card_item;
ItemClickListener itemClickListener;
CustomViewHoler(View view, ItemClickListener itemClickListener) {
super(view);
tv_title =view.findViewById(R.id.title);
tv_note = view.findViewById(R.id.note);
tv_date = view.findViewById(R.id.date);
card_item = view.findViewById(R.id.card_item);
this.itemClickListener = itemClickListener;
}
#Override
public void onClick(View v) {
itemClickListener.onItemOnClick(v, getAdapterPosition());
}
}
public MainAdapter(Context context, ArrayList<Note> noter) {
this.context = context;
this.noter = noter;
}
public void notify(ArrayList<Note> noter){
if (noter != null){
noter.clear();
noter.addAll(noter);
} else {
noter = noter;
}
notifyDataSetChanged();
}
#NonNull
#Override
public CustomViewHoler onCreateViewHolder(#NonNull ViewGroup parent, final int viewType) {
final View view = LayoutInflater.from(context).inflate(R.layout.item_note, parent, false);
return new CustomViewHoler(view, itemClickListener);
}
#Override
public void onBindViewHolder(#NonNull final CustomViewHoler holder, final int position) {
final Note note = noter.get(position);
holder.tv_title.setText( noter.get(position).getTitle());
// holder.tv_title.setText(note.getTitle());
holder.tv_note.setText(note.getNote());
//holder.tv_date.setText(note.getDate());
holder.card_item.setCardBackgroundColor(note.getColor());
holder.tv_date.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, UpdateActivity.class);
intent.putExtra("note_id", note.getId());
intent.putExtra("title", noter.get(position).getTitle());
intent.putExtra("note", noter.get(position).getNote());
intent.putExtra("color", noter.get(position).getColor());
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return noter.size();
}
public interface ItemClickListener{
void onItemOnClick(View view, int position);
View.OnClickListener onItemOnClick();
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
FloatingActionButton floatingActionButton;
RecyclerView recyclerView;
SwipeRefreshLayout swipeRefresh;
RecyclerView.Adapter adapter;
AdapterView.OnItemClickListener itemClickListener;
ArrayList <Note> noter;
private int INTENT_ADD = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
noter = new ArrayList <>();
// swipeRefresh = findViewById(R.id.swipe_refresh);
recyclerView = findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new MainAdapter(MainActivity.this, noter);
recyclerView.setAdapter(adapter);
recyclerView.notify();
retrieveData();
// retrieveUpdatedData();
floatingActionButton = findViewById(R.id.add);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.add:
Intent intent = new Intent(getApplicationContext(), InsertActivity.class);
startActivityForResult(intent, INTENT_ADD);
}
}
});
}
private void retrieveData() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Retrieving data....");
progressDialog.show();
System.out.println("!!!!!!saving!!!!!!");
StringRequest stringRequest = new StringRequest(Request.Method.GET,
"http://my-noter.000webhostapp.com/notes.php",
new Response.Listener <String>() {
#Override
public void onResponse(String s) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray array = jsonObject.getJSONArray("notes");
for (int i = 0; i < array.length(); i++) {
JSONObject row = array.getJSONObject(i);
Note note = new Note(
row.getInt("note_id"),
row.getString("title"),
row.getString("note"),
row.getInt("color")
);
noter.add(note);
}
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("volleyError error" + error.getMessage());
Toast.makeText(getApplicationContext(), "Poor network connection.", Toast.LENGTH_LONG).show();
}
}) {
};
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
requestQueue.add(stringRequest);
}
private void retrieveUpdatedData() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Retrieving Updateddata....");
progressDialog.show();
System.out.println("!!!!!!!!updating!!!!!!!");
StringRequest stringRequest = new StringRequest(Request.Method.GET,
"http://my-noter.000webhostapp.com/selectAll.php",
new Response.Listener <String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("notes");
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
Note note = new Note(
object.getInt("note_id"),
object.getString("title"),
object.getString("note"),
object.getInt("color")
);
noter.add(note);
}
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("volleyError error" + error.getMessage());
Toast.makeText(getApplicationContext(), "Poor network connection.", Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
requestQueue.add(stringRequest);
}
#Override
public void onResume() {
super.onResume();
// put your code here...
adapter.notifyItemRangeChanged(0, adapter.getItemCount());
// retrieveData();
// retrieveUpdatedData();
}
}
UpdateActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update);
et_title = findViewById(R.id.title);
et_note = findViewById(R.id.note);
note_id = getIntent().getIntExtra("note_id", 0);
title = getIntent().putExtra("title", title);
note = getIntent().putExtra("note", note);
color = getIntent().getIntExtra("color", 0);
mSpectrumPalette = findViewById(R.id.palette);
mSpectrumPalette.setHorizontalScrollBarEnabled(true);
mSpectrumPalette.setFixedColumnCount(17);
mSpectrumPalette.setOnColorSelectedListener(new SpectrumPalette.OnColorSelectedListener() {
#Override
public void onColorSelected(#ColorInt int color) {
selectedColor = color;
}
});
noter = new ArrayList<>();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_update, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.update:
//Update
final int id = this.note_id();
final String title = et_title.getText().toString().trim();
final String note = et_note.getText().toString().trim();
final int color = selectedColor;
if (title.isEmpty()) {
et_title.setError("Please enter a title");
} else if (note.isEmpty()) {
et_note.setError("Please enter a note");
} else {
final StringRequest stringRequest = new StringRequest(Request.Method.POST,
"http://my-noter.000webhostapp.com/update.php",
new Response.Listener <String>() {
#Override
public void onResponse(String response) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map <String, String> getParams() {
Map <String, String> params = new HashMap <>();
params.put("note_id", String.valueOf(id));
params.put("title", title);
params.put("note", note);
params.put("color", String.valueOf(color));
return params;
}
};
final RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
return true;
//Delete
case R.id.delete:
final StringRequest stringRequest2 = new StringRequest(Request.Method.POST, "http://my-noter.000webhostapp.com/delete.php", new Response.Listener <String>() {
#Override
public void onResponse(String response) {
Toast.makeText(getApplicationContext(), "Successfully Deleted!", Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map <String, String> getParams() {
Map <String, String> params = new HashMap <>();
// params.put("note_id", String.valueOf(note_id));
return params;
}
};
final RequestQueue requestQueue2 = Volley.newRequestQueue(getApplicationContext());
requestQueue2.add(stringRequest2);
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("Confirm !");
alertDialog.setMessage("Are you sure?" );
alertDialog.setNegativeButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
requestQueue2.stop();
}
});
alertDialog.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private int note_id() {
return note_id;
}
}
` Update.PHP``
`<?php
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$note_id = $_POST['id'];
$title = $_POST['title'];
$note = $_POST['note'];
$color = $_POST['color'];
require_once('connect.php');
$query = "UPDATE `noter` SET `title`='$title', `note`='$note', `color`=' $color' WHERE 'id'=$note_id ";
if( mysqli_query($conn, $query) ) {
$response['success'] = true;
$response['message'] = "Successfully";
} else {
$response['success'] = false;
$response['message'] = "Failure!";
}
} else {
$response['success'] = false;
$response['message'] = "Error!";
}
echo json_encode($response);
?>`
`SelectAll.PHP
<?php
header("Content-type:application/json");
require_once('connect.php');
$query =mysqli_query($conn, "SELECT * FROM `noter`");
$response["notes"] = array();
while( $row = mysqli_fetch_assoc($query)){
$notes = array();
$notes ["note_id"] = $row["id"];
$notes ["title"] = $row["title"];
$notes ["note"] = $row["note"];
$notes ["color"] = $row["color"];
array_push($response["notes"], $notes);
}
echo json_encode($response);
?>
``
In you code you refere List object as a noter within method only so your changes not apply to global object noter.
try changing as below:
public void notify(ArrayList noter){
if (this.noter != null){
this.noter.clear();
this.noter.addAll(noter);
} else{
this.noter = noter;
}
notifyDataSetChanged();
}

Add Button Click Event in RecyclerView

UserAdapter.java :
public class UsersAdapter extends RecyclerView.Adapter<UsersAdapter.UsersViewHolder> {
private List<Users> usersList;
private ImageLoader imageLoader = AppController.getInstance().getImageLoader();
private Context mContext;
public class UsersViewHolder extends RecyclerView.ViewHolder {
public TextView txtUsername, txtCreatedAt;
public NetworkImageView imgUser;
public ImageButton btnMsg, btnDel;
public UsersViewHolder(View view) {
super(view);
txtUsername = (TextView) view.findViewById(R.id.txt_username);
txtCreatedAt = (TextView) view.findViewById(R.id.txt_created_at);
imgUser = (NetworkImageView) view.findViewById(R.id.img_user);
btnMsg = (ImageButton) view.findViewById(R.id.btn_msg);
btnDel = (ImageButton) view.findViewById(R.id.btn_delete);
}
}
public UsersAdapter(Context context, List<Users> usersList) {
mContext = context;
this.usersList = usersList;
}
#Override
public UsersViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.users_list_row, parent, false);
return new UsersViewHolder(itemView);
}
#Override
public void onBindViewHolder(UsersViewHolder holder, int position) {
Users users = usersList.get(position);
holder.txtUsername.setText(users.getUserName() + " " + users.getUserSurname());
holder.txtCreatedAt.setText(users.getCreatedAt());
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
holder.imgUser.setImageUrl(users.getUserImgPath(), imageLoader);
holder.btnMsg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext, "Clicked", Toast.LENGTH_SHORT);
}
});
}
#Override
public int getItemCount() {
return usersList.size();
}
}
AppliersActivity :
public class AppliersActivity extends AppCompatActivity {
private static final String TAG = AppliersActivity.class.getSimpleName();
private SQLiteHandler db;
private SessionManager session;
private ProgressDialog pDialog;
private String uid, api_key, adId;
private List<Users> usersList = new ArrayList<>();
private RecyclerView recyclerView;
private UsersAdapter mAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_appliers);
definitions();
getAppliers();
}
private void definitions() {
adId = getIntent().getStringExtra("adId");
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// SqLite database handler
db = new SQLiteHandler(getApplicationContext());
// session manager
session = new SessionManager(getApplicationContext());
if (!session.isLoggedIn()) {
logoutUser();
}
// Fetching user details from sqlite
HashMap<String, String> user = db.getUserDetails();
uid = user.get("uid");
api_key = user.get("api_key");
recyclerView = (RecyclerView) findViewById(R.id.appliers_recycler_view);
mAdapter = new UsersAdapter(getApplicationContext(), usersList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
recyclerView.setAdapter(mAdapter);
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView, new OnTouchActionListener() {
#Override
public void onLeftSwipe(View view, int position) {
}
#Override
public void onRightSwipe(View view, int position) {
}
#Override
public void onClick(View view, int position) {
String adId = usersList.get(position).getUserId();
}
}));
}
public static interface OnTouchActionListener {
public void onLeftSwipe(View view, int position);
public void onRightSwipe(View view, int position);
public void onClick(View view, int position);
}
public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private OnTouchActionListener mOnTouchActionListener;
private GestureDetectorCompat mGestureDetector;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, OnTouchActionListener onTouchActionListener) {
mOnTouchActionListener = onTouchActionListener;
mGestureDetector = new GestureDetectorCompat(context,new GestureDetector.SimpleOnGestureListener(){
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && mOnTouchActionListener != null && mGestureDetector.onTouchEvent(e)) {
mOnTouchActionListener.onClick(child, rv.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
private void getAppliers() {
// Tag used to cancel the request
String tag_string_req = "req_appliers";
pDialog.setMessage("Lütfen Bekleyin...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.GET,
ApiRoutes.URL_JOB_APPLIERS+ "/" + adId, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Appliers Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
usersList.clear();
mAdapter.notifyDataSetChanged();
JSONArray usersArray = jObj.getJSONArray("appliers");
Users users;
for (int i = 0; i < usersArray.length(); i++) {
JSONObject jsonobject = usersArray.getJSONObject(i);
users = new Users(jsonobject.getString("uid"), jsonobject.getString("name"), jsonobject.getString("surname"), ApiRoutes.FOLDER_IMG + "/" + jsonobject.getString("uid") + "/profile_img.png", jsonobject.getString("created_at"));
usersList.add(users);
}
mAdapter.notifyDataSetChanged();
} else {
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "User Ads Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
headers.put("Authorization", api_key);
return headers;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
/**
* Logging out the user. Will set isLoggedIn flag to false in shared
* preferences Clears the user data from sqlite users table
* */
private void logoutUser() {
session.setLogin(false);
db.deleteUsers();
// Launching the login activity
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
finish();
}
}
I have two imagebutton on recyclerviewer' s rows. I want to add click event for each row. I sent the applicationcontext to an adapter from activity. And i added to onclicklistener event in adapter class. But it does not show toast on the screen. How can i solve this problem ?
You don't call show() method of Toast in your adapter class.
Change it as following
holder.btnMsg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext, "Clicked", Toast.LENGTH_SHORT).show();
}
});

Load new data when refresh RecyclerView

I want develop android application for one website. I read website posts from json and show its in RecyclerView every 10 posts and when user scrolling on RecyclerView show more 10 post and go to end! in this project i use okHTTP v3 and RecyclerView!
I want gonna put a button and when click on this button, load new data (if there was new data).
Button codes:
// Refresh Data
toolbar_refresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LoadData();
}
});
}
Main Activity codes:
public class Main_page extends AppCompatActivity {
private static final long RIPPLE_DURATION = 250;
private Toolbar toolbar;
private RelativeLayout root;
private ImageView menu_image, toolbar_refresh;
private RecyclerView main_recyclerView;
private MainAdapter_loadMore mAdaper;
private List<MainDataModel> dataModels = new ArrayList<MainDataModel>();
protected Handler handler;
private RelativeLayout loadLayout;
private LinearLayoutManager mLayoutManager;
private int pageCount = 1;
String ServerAddress = ServerIP.getIP();
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_page);
if (!EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().register(this);
}
// Init
handler = new Handler();
context = getApplicationContext();
toolbar = (Toolbar) findViewById(R.id.main_toolbar);
mLayoutManager = new LinearLayoutManager(this);
loadLayout = (RelativeLayout) findViewById(R.id.main_empty_layout);
toolbar_refresh = (ImageView) toolbar.findViewById(R.id.toolbar_update);
// Toolbar
if (toolbar != null) {
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(null);
}
// Load First Data
LoadData();
// Menu
root = (RelativeLayout) findViewById(R.id.main_root);
View guillotineMenu = LayoutInflater.from(this).inflate(R.layout.menu_layout, null);
root.addView(guillotineMenu);
menu_image = (ImageView) toolbar.findViewById(R.id.toolbar_logo);
new GuillotineAnimation.GuillotineBuilder(guillotineMenu, guillotineMenu.findViewById(R.id.menu_layout_image), menu_image)
.setStartDelay(RIPPLE_DURATION)
.setActionBarViewForAnimation(toolbar)
.setClosedOnStart(true)
.build();
// RecyclerView and setData
main_recyclerView = (RecyclerView) findViewById(R.id.main_recycler);
main_recyclerView.setHasFixedSize(true);
main_recyclerView.setLayoutManager(mLayoutManager);
mAdaper = new MainAdapter_loadMore(this, main_recyclerView, dataModels);
main_recyclerView.setAdapter(mAdaper);
// Load More data
mAdaper.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
dataModels.add(null);
mAdaper.notifyItemInserted(dataModels.size() - 1);
LoadMoreData(pageCount);
}
});
// Refresh Data
toolbar_refresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LoadData();
}
});
}
#Subscribe
public void onEvent(List<MainDataModel> mainInfoModels) {
if (dataModels.size() > 0) {
dataModels.remove(dataModels.size() - 1);
mAdaper.notifyItemRemoved(dataModels.size());
mAdaper.setLoaded();
}
mAdaper.add(mainInfoModels);
mAdaper.notifyDataSetChanged();
pageCount++;
if (dataModels.isEmpty()) {
main_recyclerView.setVisibility(View.GONE);
loadLayout.setVisibility(View.VISIBLE);
} else {
main_recyclerView.setVisibility(View.VISIBLE);
loadLayout.setVisibility(View.GONE);
}
}
private void LoadData() {
MainDataInfo dataInfo = new MainDataInfo();
// here getMainDataInfo() should return the server response
dataInfo.getMainDataInfo(this);
}
private void LoadMoreData(int pageNumber) {
MainDataInfo_loadMore dataInfo_loadMore = new MainDataInfo_loadMore();
// here getMainDataInfo() should return the server response
dataInfo_loadMore.getMainDataInfo_loadMore(this, pageNumber);
}
}
Adapter codes:
public class MainAdapter_loadMore extends RecyclerView.Adapter {
private List<MainDataModel> mDateSet;
private Context mContext;
private final int VIEW_ITEM = 1;
private final int VIEW_PROG = 0;
// The minimum amount of items to have below your current scroll position
// before loading more.
private int visibleThreshold = 5;
private int lastVisibleItem, totalItemCount;
private boolean loading;
private OnLoadMoreListener onLoadMoreListener;
public MainAdapter_loadMore(Context context, RecyclerView recyclerView, List<MainDataModel> dataSet) {
this.mContext = context;
this.mDateSet = dataSet;
if (recyclerView.getLayoutManager() instanceof LinearLayoutManager) {
final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView
.getLayoutManager();
recyclerView
.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView,
int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
totalItemCount = linearLayoutManager.getItemCount();
lastVisibleItem = linearLayoutManager
.findLastVisibleItemPosition();
if (!loading
&& totalItemCount <= (lastVisibleItem + visibleThreshold)) {
// End has been reached
// Do something
if (onLoadMoreListener != null) {
onLoadMoreListener.onLoadMore();
}
loading = true;
}
}
});
}
}
#Override
public int getItemViewType(int position) {
return mDateSet.get(position) != null ? VIEW_ITEM : VIEW_PROG;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder vh;
if (viewType == VIEW_ITEM) {
View v = LayoutInflater.from(parent.getContext()).inflate(
R.layout.post_card_layout, parent, false);
vh = new DataViewHolder(v);
} else {
View v = LayoutInflater.from(parent.getContext()).inflate(
R.layout.progressbar_item, parent, false);
vh = new ProgressViewHolder(v);
}
return vh;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof DataViewHolder) {
((DataViewHolder) holder).main_post_title.setText(mDateSet.get(position).getTitle());
Glide.with(mContext)
.load(mDateSet.get(position).getThumbnail())
.placeholder(R.drawable.post_image)
.crossFade()
.into(((DataViewHolder) holder).main_post_image);
((DataViewHolder) holder).main_post_content.setText(Html.fromHtml(mDateSet.get(position).getContent()));
} else {
((ProgressViewHolder) holder).progressBar.setVisibility(View.VISIBLE);
}
}
public void setLoaded() {
loading = false;
}
#Override
public int getItemCount() {
return mDateSet.size();
}
public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) {
this.onLoadMoreListener = onLoadMoreListener;
}
public void remove(int position) {
mDateSet.remove(position);
notifyItemRemoved(position);
}
public void clear() {
mDateSet.clear();
notifyDataSetChanged();
}
public void add(List<MainDataModel> models) {
mDateSet.addAll(models);
notifyDataSetChanged();
}
public void update(List<MainDataModel> models) {
mDateSet.clear();
mDateSet.addAll(models);
notifyDataSetChanged();
}
public class DataViewHolder extends RecyclerView.ViewHolder {
private TextView main_post_title, main_post_content;
private ImageView main_post_image;
public DataViewHolder(View itemView) {
super(itemView);
main_post_title = (TextView) itemView.findViewById(R.id.post_content_title);
main_post_image = (ImageView) itemView.findViewById(R.id.post_picture_image);
main_post_content = (TextView) itemView.findViewById(R.id.post_content_text);
}
}
public static class ProgressViewHolder extends RecyclerView.ViewHolder {
public AVLoadingIndicatorView progressBar;
public ProgressViewHolder(View v) {
super(v);
progressBar = (AVLoadingIndicatorView) v.findViewById(R.id.avloadingIndicatorView);
}
}
}
AsyncTask code (LoadData codes) :
public class MainDataInfo {
private Context mContext;
private String ServerAddress = ServerIP.getIP();
public void getMainDataInfo(Context context) {
mContext = context;
new getInfo().execute(ServerAddress + "page=1");
}
private class getInfo extends AsyncTask<String, Void, String> {
EventBus bus = EventBus.getDefault();
private String ou_response;
private List<MainDataModel> infoModels;
#Override
protected void onPreExecute() {
CustomProcessDialog.createAndShow(mContext);
infoModels = new ArrayList<>();
}
#Override
protected String doInBackground(String... params) {
OkHttpClient client = new OkHttpClient();
//String url = (String) params[0];
Request request = new Request.Builder()
.url(ServerAddress + "page=1")
.cacheControl(CacheControl.FORCE_NETWORK)
.build();
Response response;
try {
response = client.newCall(request).execute();
ou_response = response.body().string();
response.body().close();
if (ou_response != null) {
try {
JSONObject postObj = new JSONObject(ou_response);
JSONArray postsArray = postObj.optJSONArray("posts");
infoModels = new ArrayList<>();
for (int i = 0; i <= infoModels.size(); i++) {
JSONObject postObject = (JSONObject) postsArray.get(i);
JSONObject images = postObject.optJSONObject("thumbnail_images");
JSONObject imagesPair = images.optJSONObject("medium");
int id = postObject.getInt("id");
String title = postObject.getString("title");
String content = postObject.getString("content");
String thumbnail = imagesPair.getString("url");
Log.d("Data", "Post id: " + id);
Log.d("Data", "Post title: " + title);
Log.d("Data", "Post title: " + thumbnail);
//Use the title and id as per your requirement
infoModels.add(new MainDataModel(id, title, content, thumbnail));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
return ou_response;
}
#Override
protected void onPostExecute(String result) {
CustomProcessDialog.dissmis();
if (result != null) {
bus.post(infoModels);
}
}
}
}
When use this method LoadData(); in button action, not load new data just copy fist 10 post and load again this first 10 post!
How can i fix it and when click on Button click action, load new data ?
Attention : Please don't give me negative points, help me and i really need you helps! thanks all <3
Add this in your MainDataInfo class:
public class MainDataInfo {
private MainDataListener mListener;
public interface MainDataListener {
void onDataReceived(List<MainDataModel> infoModels);
}
public void setDataListener(MainDataListener listener){
this.mListener = listener;
}
#Override
protected void onPostExecute(String result) {
CustomProcessDialog.dissmis();
if (result != null) {
bus.post(infoModels);
//add this
if(mListener !=null)
mListener.onDataReceived(infoModels);
}
}
}
In your activity Main_page:
//implement the maindata listener
public class Main_page extends AppCompatActivity implement MainDataInfo.MainDataListener { }
Override the interface's method in the activity class
#Override
void onDataReceived(List<MainDataModel> infoModels){
// here set your recyclerview adapter
mAdaper.update(infoModels);
mAdaper.notifyDataSetChanged();
}

Updating data in a recyclerview

In my project a read data from a CMS I created through a JSON response. My problem is when I click the refresh button the data are read twice!. Here is my fragment's code.
public class FootballNews extends Fragment {
public static final String TAG = "ManuApp";
private static final String IMAGE_URL = "http://xxx//manucms/football_news_images/" ;
private List<FootballNewsObject> listItemsList;
private RecyclerView mRecyclerView;
private FootballNewsAdapter adapter;
public FootballNews() {
// Required empty public constructor
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setRetainInstance(true);
View v = inflater.inflate(R.layout.fragment_football_news, container, false);
// Inflate the layout for this fragment
listItemsList = new ArrayList<FootballNewsObject>();
mRecyclerView = (RecyclerView)v.findViewById(R.id.recycler_view);
//mRecyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getActivity()).color(Color.BLACK).build());
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(linearLayoutManager);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
updateList();
}
public void updateList() {
//declare the adapter and attach it to the recyclerview
adapter = new FootballNewsAdapter(getActivity(), listItemsList);
mRecyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(getActivity());
// Clear the adapter because new data is being added from a new subreddit
//adapter.clearAdapter();
//showPD();
// Request a string response from the provided URL.
JsonArrayRequest jsObjRequest = new JsonArrayRequest(Request.Method.GET, Config.URL_FOOTBALL_NEWS, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
//hidePD();
// Parse json data.
// Declare the json objects that we need and then for loop through the children array.
// Do the json parse in a try catch block to catch the exceptions
try {
for (int i = 0; i < response.length(); i++) {
JSONObject post = response.getJSONObject(i);
FootballNewsObject item = new FootballNewsObject();
item.setTitle(post.getString("title"));
item.setImage(IMAGE_URL + post.getString("news_image"));
item.setArticle(post.getString("article"));
listItemsList.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
// Update list by notifying the adapter of changes
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
//hidePD();
}
});
jsObjRequest.setRetryPolicy(new RetryPolicy() {
#Override
public int getCurrentTimeout() {
return 50000;
}
#Override
public int getCurrentRetryCount() {
return 50000;
}
#Override
public void retry(VolleyError error) throws VolleyError {
}
});
queue.add(jsObjRequest);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
getActivity().getMenuInflater().inflate(R.menu.main, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if(id == R.id.refresh){
if(isOnline()) {
updateList();
}else{
Toast.makeText(getActivity(),"There is no internet connection",Toast.LENGTH_SHORT).show();
}
}
return super.onOptionsItemSelected(item);
}
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
}
Basically I am running the updateList method twice. Once in the onActivityCreated(...) method,and secondly inside the onOptionsItemSelected(...).
Finally here is my adapter.
public class FootballNewsAdapter extends RecyclerView.Adapter<FootballNewsRowHolder>{
private List<FootballNewsObject> footballNewsObjectList;
private Context mContext;
private ImageLoader mImageLoader;
private int focused = 0;
public FootballNewsAdapter(Activity activity, List<FootballNewsObject> footballNewsObjectList){
this.footballNewsObjectList = footballNewsObjectList;
this.mContext = activity;
}
#Override
public FootballNewsRowHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.football_news_row,null);
final FootballNewsRowHolder holder = new FootballNewsRowHolder(v);
return holder;
}
#Override
public void onBindViewHolder(FootballNewsRowHolder holder, int position) {
final FootballNewsObject listItems = footballNewsObjectList.get(position);
holder.itemView.setSelected(focused==position);
holder.getLayoutPosition();
mImageLoader = AppController.getInstance().getImageLoader();
holder.thumbnail.setImageUrl(listItems.getImage(),mImageLoader);
holder.thumbnail.setDefaultImageResId(R.drawable.reddit_placeholder);
holder.name.setText(Html.fromHtml(listItems.getTitle()));
holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String title = listItems.getTitle();
String article = listItems.getArticle();
String image = listItems.getImage();
Intent i = new Intent(mContext, Extras.class);
i.putExtra("title",title);
i.putExtra("article",article);
i.putExtra("image",image);
mContext.startActivity(i);
//Toast.makeText(mContext,"You clicked",Toast.LENGTH_SHORT).show();
//Intent intent = new Intent(mContext,WebActivity.class);
//intent.putExtra("url",postUrl);
// mContext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return (null != footballNewsObjectList?footballNewsObjectList.size() :0 );
}
}
Any ideas?
Thanks
You are adding to your list in your refresh method, instead of updating. Add
listItemsList.clear();
at the beginning of your refresh function (updateList).

How to send object value from RecyclerView Item to Another Activity

From a JSON array that I am parsing, I want to send a particular object value (using intent putExtra) to another activity. I have read this this question
and the accepted answer but I don't want to send all the values, in my case I only want to send the news_id as an integer to NewsDetails.class.
And I tried using the accepted answer to do it but I got stuck.
MainActivity
public class MainActivity extends AppCompatActivity{
private final String TAG = "MainActivity";
//Creating a list of newss
private List<NewsItems> mNewsItemsList;
//Creating Views
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "Device rotated and onCreate called");
//Initializing Views
recyclerView = (RecyclerView) findViewById(R.id.news_recycler);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
//Initializing the newslist
mNewsItemsList = new ArrayList<>();
adapter = new NewsAdapter(mNewsItemsList, this);
recyclerView.setAdapter(adapter);
//Caling method to get data
getData();
}
//This method will get data from the web api
private void getData(){
Log.d(TAG, "getData called");
//Showing progress dialog
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setCancelable(false);
mProgressDialog.setMessage(this.getResources().getString(R.string.load_news));
mProgressDialog.show();
//Creating a json request
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(ConfigNews.GET_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, "onResponse called");
//Dismissing the progress dialog
if (mProgressDialog != null) {
mProgressDialog.hide();
}
/*progressDialog.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){
Log.d(TAG, "Parsing array");
for(int i = 0; i<array.length(); i++) {
NewsItems newsItem = new NewsItems();
JSONObject jsonObject = null;
try {
jsonObject = array.getJSONObject(i);
newsItem.setNews_title(jsonObject.getString(ConfigNews.TAG_NEWS_TITLE));
newsItem.setNews_excerpt(jsonObject.getString(ConfigNews.TAG_NEWS_EXCERPT));
newsItem.setNewsId(jsonObject.getInt(ConfigNews.TAG_NEWS_ID));
} catch (JSONException w) {
w.printStackTrace();
}
mNewsItemsList.add(newsItem);
}
adapter.notifyItemRangeChanged(0, adapter.getItemCount());
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy called");
if (mProgressDialog != null){
mProgressDialog.dismiss();
Log.d(TAG, "mProgress dialog dismissed");
}
}
}
NewsItems class
public class NewsItems {
private String news_title;
private String news_excerpt;
private int news_id;
public String getNews_title() {
return news_title;
}
public void setNews_title(String news_title) {
this.news_title = news_title;
}
public String getNews_excerpt() {
return news_excerpt;
}
public void setNews_excerpt(String news_excerpt) {
this.news_excerpt = news_excerpt;
}
public int getNews_id() {
return news_id;
}
public void setNews_id(int news_id) {
this.news_id = news_id;
}
}
NewsAdapter
public class NewsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
private ImageLoader imageLoader;
private Context mContext;
//List of newss
private List<NewsItems> mNewsItems;
private final int VIEW_ITEM = 0;
private final int VIEW_PROG = 1;
private int lastPosition = -1;
public NewsAdapter(List<NewsItems> newsItems, Context context) {
super();
//Getting all newss
this.mNewsItems = newsItems;
this.mContext = context;
}
#Override
public int getItemViewType(int position) {
if (isPositionItem(position))
return VIEW_ITEM;
return VIEW_PROG;
}
private boolean isPositionItem(int position) {
return position != getItemCount()-1;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder (ViewGroup parent, int viewType) {
if (viewType == VIEW_ITEM) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.news_summ, parent, false);
return new TextViewHolder(v, mContext);
} else if (viewType == VIEW_PROG){
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recyclerfooter, parent, false);
return new ProgressViewHolder(v);
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof TextViewHolder) {
NewsItems newsList = mNewsItems.get(position);
((TextViewHolder) holder).newsTitle.setText(newsList.getNews_title());
((TextViewHolder) holder).newsExcerpt.setText(newsList.getNews_excerpt());
((TextViewHolder) holder).newsId.setText(String.valueOf(newsList.getNewsId()));
} else {
((ProgressViewHolder) holder).progressBar.setIndeterminate(true);
((ProgressViewHolder) holder).loadButton.setText(R.string.reload);
}
}
#Override
public int getItemCount(){
//Return the number of items in the data set
return mNewsItems.size();
}
public static class TextViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView newsTitle,newsExcerpt, newsId;
public ImageButton imageButton;
public NewsItems dNewsItems;
private Context context;
public TextViewHolder (final View newsView, final Context context) {
super(newsView);
this.context = context;
newsTitle = (TextView) newsView.findViewById(R.id.news_title);
newsExcerpt = (TextView) newsView.findViewById(R.id.news_excerpt);
newsId = (TextView) newsView.findViewById(R.id.news_id);
newsExcerpt.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == newsExcerpt.getId()) {
Intent intent = new Intent(context, NewsDetails.class);
Bundle bundle = new Bundle();
bundle.putSerializable("PostId", //This is where I got confused);
}
}
}
}
public static class ProgressViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
Button loadButton;
ProgressBar progressBar;
public ProgressViewHolder(View footerView){
super(footerView);
loadButton = (Button) footerView.findViewById(R.id.reload_button);
progressBar = (ProgressBar) footerView.findViewById(R.id.progress_load);
loadButton.setOnClickListener(this);
if(NetworkCheck.isAvailableAndConnected(footerView.getContext())) {
progressBar.setVisibility(View.VISIBLE);
} else if (!NetworkCheck.isAvailableAndConnected(footerView.getContext())) {
loadButton.setVisibility(View.VISIBLE);
}
}
#Override
public void onClick(View v) {
if (v.getId() == loadButton.getId()) {
//
}
}
}
}
You can send single value also instead of complete object like this -
#Override
public void onClick(View v) {
if (v.getId() == newsExcerpt.getId()) {
Intent intent = new Intent(context, NewsDetails.class);
intent.putExtra("PostId",<your_news_id_here>);
startActivity(intent);
}
}
}
In your case, remove onClick(View v) and change your onBindViewHolder() to setOnClickListener() on newsExcerpt like this -
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof TextViewHolder) {
NewsItems newsList = mNewsItems.get(position);
((TextViewHolder) holder).newsTitle.setText(newsList.getNews_title());
((TextViewHolder) holder).newsExcerpt.setText(newsList.getNews_excerpt());
((TextViewHolder) holder).newsId.setText(String.valueOf(newsList.getNewsId()));
((TextViewHolder) holder).newsExcerpt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, NewsDetails.class);
intent.putExtra("PostId",newsList.getNewsId()); //Any getter of your class you want
startActivity(intent);
});
} else {
((ProgressViewHolder) holder).progressBar.setIndeterminate(true);
((ProgressViewHolder) holder).loadButton.setText(R.string.reload);
}
}
I don't want to send all the values
You dont' have to send all, It's up to you and your needs.
Intent i = new Intent(context, DestActivity.class);
i.putExtra(KEY_NEWS_ID, news_id );
On the other end:
int news_id = getIntent().getIntExtra(KEY_NEWS_ID, defaultValue);

Categories

Resources