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();
}
Related
I have a RecyclerView of questions (which are saved and retrieved from database) and seekbars (which I save in database).
Link to image
After clicking on SUBMIT EXTRA QUESTIONS there is a dialog which appears
Link to image
I want after clicking on Okay the progress of ALL seekbars to be 0.
I tried to do this submitExpenseData(jsonArrayQuestion.toString(), getId, jsonArrayAnswer.toString(), formatter.format(date));
holder.seekBar.setProgress(0);
But It changes only the progress of the last seekbar. Does anyone have any idea?
public class ExtraQuestionAdapter extends RecyclerView.Adapter<ExtraQuestionAdapter.ExtraQuestionViewHolder> {
private Context mCntx;
private List<ExtraQuestion> extraQuestionList;
private OnExtraAnswerListener onExtraAnswerListener;
private Button btn_submit_extra_questions;
private View rootView;
ArrayList<Integer> answersArray;
private Integer[] array = {};
String getId;
SessionManager sessionManager;
private Dialog dialog;
public ExtraQuestionAdapter(Context mCntx, List<ExtraQuestion> extraQuestionList, OnExtraAnswerListener onExtraAnswerListener) {
this.mCntx = mCntx;
this.extraQuestionList = extraQuestionList;
this.onExtraAnswerListener = onExtraAnswerListener;
}
#NonNull
#Override
public ExtraQuestionViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mCntx);
View view = inflater.inflate(R.layout.extra_question_layout, parent, false);
sessionManager = new SessionManager(mCntx);
HashMap<String, String> user = sessionManager.getUserDetail();
mCntx = parent.getContext();
rootView = ((Activity) mCntx).getWindow().getDecorView().findViewById(android.R.id.content);
//set the size of the array with answers to be equal to the size of the array with questions
array = new Integer[extraQuestionList.size()];
//initialise the array with answers with 0
for (int i = 0; i < extraQuestionList.size(); i++) {
array[i] = 0;
}
getId = user.get(sessionManager.ID);
btn_submit_extra_questions = rootView.findViewById(R.id.btn_submit_extra_questions);
ExtraQuestionViewHolder extraQuestionViewHolder = new ExtraQuestionViewHolder(view, onExtraAnswerListener);
return extraQuestionViewHolder;
}
#Override
public void onBindViewHolder(#NonNull ExtraQuestionViewHolder holder, int position) {
ExtraQuestion extraQuestion = extraQuestionList.get(position);
holder.title.setText(extraQuestion.getExtra_question());
holder.seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
array[holder.getAdapterPosition()] = seekBar.getProgress();
}
});
btn_submit_extra_questions.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog = new Dialog(mCntx);
dialog.setContentView(R.layout.dialog_submit);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
dialog.getWindow().setBackgroundDrawable(mCntx.getDrawable(R.drawable.dialog_background));
}
dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
dialog.setCancelable(true);
Button finalSubmit = dialog.findViewById(R.id.btn_submit);
Button cancelSubmit = dialog.findViewById(R.id.btn_cancel);
ImageView info = dialog.findViewById(R.id.info);
TextView termsConditions = dialog.findViewById(R.id.textView3);
// Cancel button in the dialog
cancelSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
//Okay button in the dialog
finalSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//fill the arraylist of answers with the array of answers
answersArray = new ArrayList<>(Arrays.asList(array));
ArrayList<Integer> FAnswerArray = new ArrayList<>();
ArrayList<Integer> FQuestionArray = new ArrayList<>();
if (!answersArray.isEmpty()) {
for (int i = 0; i < answersArray.size(); i++) {
FAnswerArray.add(answersArray.get(i));
FQuestionArray.add(i + 1);
}
}
JSONArray jsonArrayQuestion = new JSONArray();
for (Integer question : FQuestionArray) {
jsonArrayQuestion.put(question);
}
JSONArray jsonArrayAnswer = new JSONArray();
for (Integer answer : FAnswerArray) {
jsonArrayAnswer.put(answer);
}
dialog.dismiss();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date(System.currentTimeMillis());
submitExpenseData(jsonArrayQuestion.toString(), getId, jsonArrayAnswer.toString(), formatter.format(date));
}
});
//Info button in the dialog
info.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mCntx.getApplicationContext(), TermsConditionsActivity.class);
mCntx.startActivity(intent);
}
});
//Terms and conditions in the dialog
termsConditions.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mCntx.getApplicationContext(), TermsConditionsActivity.class);
mCntx.startActivity(intent);
}
});
dialog.show();
}
});
}
private void submitExpenseData(String extra_questions_id, String users_id, String extra_answer, String timeStamp_date) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.EXTRA_ANSWERS_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//we get the successful in String response
Log.e("response", response);
try {
JSONObject jsonObject = new JSONObject(response.substring(response.indexOf("{"), response.lastIndexOf("}") + 1));
String success = jsonObject.getString("success");
if (success.equals("1")) {
sessionManager.saveAnswersOfTheDay(extra_questions_id, users_id, extra_answer, timeStamp_date);
Toast.makeText(mCntx.getApplicationContext(), R.string.successQuestionsOfTheDay, Toast.LENGTH_SHORT).show();
}
if (success.equals("alreadySubmitted")) {
Toast.makeText(mCntx.getApplicationContext(), R.string.submit_extra_questions_once_a_day, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(mCntx.getApplicationContext(), "Error! " + e.toString(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("sellresponseerror", "" + error.toString());
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("extra_questions_id", extra_questions_id);
params.put("users_id", users_id);
params.put("extra_answer", extra_answer);
params.put("timeStamp_date", timeStamp_date);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(mCntx);
requestQueue.add(stringRequest);
}
#Override
public int getItemCount() {
return extraQuestionList.size();
}
public class ExtraQuestionViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView title;
SeekBar seekBar;
OnExtraAnswerListener onExtraAnswerListener;
public ExtraQuestionViewHolder(#NonNull View itemView, OnExtraAnswerListener onExtraAnswerListener) {
super(itemView);
title = itemView.findViewById(R.id.textViewTitle);
seekBar = itemView.findViewById(R.id.seekBar);
this.onExtraAnswerListener = onExtraAnswerListener;
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
onExtraAnswerListener.onExtraAnswerClick(getAdapterPosition());
}
}
public interface OnExtraAnswerListener {
void onExtraAnswerClick(int position);
}
}
The whole concept I am using is when i clicked a textview inside a single list item of list view, i called a method defined in the activity from my adapter class and then in that method , i have hit an api and when i get the response , I again load the list and the i got this error.
My adapter class..
public class NewsFeedAdapter extends BaseAdapter {
Context context;
ArrayList<NewsFeed> newsFeedArrayList;
String residentId;
ViewHolder viewHolder;
//NewsFeedActivity newsFeedActivity;
public NewsFeedAdapter(Context context, ArrayList<NewsFeed> newsFeedArrayList,String residentId) {
this.context = context;
this.newsFeedArrayList = newsFeedArrayList;
this.residentId = residentId;
}
private class ViewHolder{
ImageView friendProfilePic,feedImage,deletePostBtn,likeBtn,commentBtn;
TextView friendName,postTime,feedPostTxt,totalLikes,totalComments;
RelativeLayout likeBtnLayout,commentBtnLayout,feedPostImageLayout;
}
#Override
public int getCount() {
return newsFeedArrayList.size();
}
#Override
public Object getItem(int i) {
return newsFeedArrayList.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (view == null){
viewHolder = new ViewHolder();
view = layoutInflater.inflate(R.layout.news_feed_list_item,viewGroup,false);
viewHolder.friendProfilePic = view.findViewById(R.id.friend_profile_pic);
viewHolder.friendName = view.findViewById(R.id.friend_name);
viewHolder.postTime = view.findViewById(R.id.feed_post_date);
viewHolder.feedImage = view.findViewById(R.id.feed_post_image);
viewHolder.feedPostTxt = view.findViewById(R.id.feed_post_text);
viewHolder.deletePostBtn = view.findViewById(R.id.delete_post_btn);
viewHolder.likeBtn = view.findViewById(R.id.like_btn);
viewHolder.commentBtn = view.findViewById(R.id.comment_btn);
viewHolder.totalLikes = view.findViewById(R.id.no_of_likes);
viewHolder.totalComments = view.findViewById(R.id.no_of_comments);
viewHolder.likeBtnLayout = view.findViewById(R.id.like_btn_layout);
viewHolder.commentBtnLayout = view.findViewById(R.id.comment_btn_layout);
viewHolder.feedPostImageLayout = view.findViewById(R.id.feed_post_image_layout);
view.setTag(viewHolder);
}
else {
viewHolder = (ViewHolder) view.getTag();
}
//Log.w(AppConfig.TAG,"position is "+i);
final NewsFeed newsFeed = newsFeedArrayList.get(i);
viewHolder.feedImage.setBottom(0);
Glide.with(context).load(newsFeed.getFriendprofilePic())
.asBitmap().centerCrop().into(new BitmapImageViewTarget(viewHolder.friendProfilePic) {
#Override
protected void setResource(Bitmap resource) {
RoundedBitmapDrawable circularBitmapDrawable =
RoundedBitmapDrawableFactory.create(context.getResources(), resource);
circularBitmapDrawable.setCircular(true);
viewHolder.friendProfilePic.setImageDrawable(circularBitmapDrawable);
}
});
viewHolder.friendName.setText(newsFeed.getFriendName());
viewHolder.postTime.setText(newsFeed.getPostTime());
//Log.w(AppConfig.TAG,"pos is "+i+newsFeed.getFeedImage()+"");
if (!newsFeed.getFeedImage().equals("null")){
viewHolder.feedPostImageLayout.setVisibility(View.VISIBLE);
Glide.with(context).load(newsFeed.getFeedImage())
.thumbnail(0.5f)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(viewHolder.feedImage);
}
else {
viewHolder.feedPostImageLayout.setVisibility(View.GONE);
}
viewHolder.feedPostTxt.setText(newsFeed.getFeedPostTxt());
if (newsFeed.getFriendId().equals(residentId)){
viewHolder.deletePostBtn.setVisibility(View.VISIBLE);
}
else {
viewHolder.deletePostBtn.setVisibility(View.GONE);
}
if (Integer.parseInt(newsFeed.getTotalLikes())>0){
viewHolder.totalLikes.setVisibility(View.VISIBLE);
viewHolder.totalLikes.setText(newsFeed.getTotalLikes()+" Likes");
}
else {
viewHolder.totalLikes.setVisibility(View.GONE);
}
if (Integer.parseInt(newsFeed.getTotalComments())>0){
viewHolder.totalComments.setVisibility(View.VISIBLE);
viewHolder.totalComments.setText(newsFeed.getTotalComments()+" Comments");
}
else {
viewHolder.totalComments.setVisibility(View.GONE);
}
viewHolder.totalLikes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, LikesResidentNamesActivity.class);
intent.putExtra(AppConfig.POST_ID,newsFeed.getPostId());
context.startActivity(intent);
}
});
viewHolder.totalComments.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, AllCommentsActivity.class);
intent.putExtra(AppConfig.POST_ID,newsFeed.getPostId());
context.startActivity(intent);
}
});
viewHolder.likeBtnLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
NewsFeedActivity newsFeedActivity = (NewsFeedActivity) context;
newsFeedActivity.likeDislikePost(newsFeed.getPostId());
}
});
viewHolder.commentBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addComment(newsFeed);
}
});
viewHolder.commentBtnLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addComment(newsFeed);
}
});
viewHolder.deletePostBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
deletePost(newsFeed.getPostId());
}
});
return view;
}
private void deletePost(final String postId){
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Delete Confirm?");
builder.setMessage("Are you sure want to delete this post?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
NewsFeedActivity newsFeedActivity = (NewsFeedActivity) context;
newsFeedActivity.deletePost(postId);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
private void addComment(NewsFeed newsFeed){
Intent intent = new Intent(context, AllCommentsActivity.class);
intent.putExtra(AppConfig.POST_ID,newsFeed.getPostId());
context.startActivity(intent);
}
}
and this is my activity code..
public class NewsFeedActivity extends AppCompatActivity {
TextView toolbarTitle;
ImageView backBtn;
ListView newsFeedListView;
ArrayList<NewsFeed> newsFeedArrayList = new ArrayList<>();
NewsFeedAdapter newsFeedAdapter;
HashMap<String,String> residentDetails;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news_feed);
toolbarTitle = (TextView) findViewById(R.id.toolbar_title);
backBtn = (ImageView) findViewById(R.id.back_btn);
progressBar = (ProgressBar) findViewById(R.id.progress_bar);
toolbarTitle.setText("News Feed");
backBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AppConfig.goBackToParentActivity(NewsFeedActivity.this);
}
});
DatabaseManager databaseManager = new DatabaseManager(NewsFeedActivity.this);
residentDetails = databaseManager.getResidentDetails();
newsFeedListView = (ListView) findViewById(R.id.news_feed_list_view);
View newsFeedListViewHeader = getLayoutInflater().inflate(R.layout.news_feed_list_header,null);
newsFeedListView.addHeaderView(newsFeedListViewHeader);
newsFeedAdapter = new NewsFeedAdapter(this,newsFeedArrayList,residentDetails.get(AppConfig.RESIDENT_ID));
newsFeedListView.setAdapter(newsFeedAdapter);
loadNewsFeed();
}
private void loadNewsFeed(){
newsFeedArrayList.clear();
StringRequest stringRequest = new StringRequest(Request.Method.POST,AppConfig.NEWS_FEED_METHOD, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressBar.setVisibility(View.GONE);
Log.w(AppConfig.TAG,response);
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getInt(AppConfig.STATUS_CODE) == 201){
JSONArray newsFeedArray = jsonObject.getJSONArray(AppConfig.RESPONSE);
if (newsFeedArray.length()>0) {
for (int i = 0; i < newsFeedArray.length(); i++) {
JSONObject newsFeedObject = newsFeedArray.getJSONObject(i);
newsFeedArrayList.add(new NewsFeed(newsFeedObject.getString(AppConfig.POST_ID), newsFeedObject.getString(AppConfig.RESIDENT_ID), newsFeedObject.getString(AppConfig.RESIDENT_NAME), newsFeedObject.getString(AppConfig.RESIDENT_IMAGE),
AppConfig.strToDate(newsFeedObject.getString(AppConfig.POST_DATE)), newsFeedObject.getString(AppConfig.POST_IMG), newsFeedObject.getString(AppConfig.POST_STATUS),
newsFeedObject.getString(AppConfig.TOTAL_LIKES), newsFeedObject.getString(AppConfig.TOTAL_COMMENTS)));
}
newsFeedAdapter.notifyDataSetChanged();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressBar.setVisibility(View.GONE);
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put(AppConfig.RESIDENT_SOCIETY_ID,residentDetails.get(AppConfig.RESIDENT_SOCIETY_ID));
params.put(AppConfig.RESIDENT_ID,residentDetails.get(AppConfig.RESIDENT_ID));
Log.w(AppConfig.TAG,params+"");
return params;
}
};
AppController.getInstance().addToRequestQueue(stringRequest);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == AppConfig.INTENT_REQUEST_CODE){
newsFeedArrayList.clear();
loadNewsFeed();
}
}
public void deletePost(String postId){
StringRequest stringRequest = new StringRequest(Request.Method.PUT, AppConfig.DELETE_POST_METHOD+postId, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.w(AppConfig.TAG,response);
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getInt(AppConfig.STATUS_CODE)==201){
Toast.makeText(NewsFeedActivity.this, "Your post has been deleted successfully!", Toast.LENGTH_SHORT).show();
newsFeedArrayList.clear();
loadNewsFeed();
}
else {
Toast.makeText(NewsFeedActivity.this, "Some error occured!", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
AppController.getInstance().addToRequestQueue(stringRequest);
}
public void likeDislikePost(final String postId){
StringRequest stringRequest = new StringRequest(Request.Method.POST, AppConfig.LIKE_UNLIKE_POST_METHOD, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.w(AppConfig.TAG,response);
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getInt(AppConfig.STATUS_CODE) == 201){
loadNewsFeed();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put(AppConfig.RESIDENT_SOCIETY_ID,residentDetails.get(AppConfig.RESIDENT_SOCIETY_ID));
params.put(AppConfig.RESIDENT_ID,residentDetails.get(AppConfig.RESIDENT_ID));
params.put(AppConfig.POST_ID,postId);
Log.w(AppConfig.TAG,params+"");
return params;
}
};
AppController.getInstance().addToRequestQueue(stringRequest);
}
}
Logcat
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:411)
at android.widget.HeaderViewListAdapter.isEnabled(HeaderViewListAdapter.java:164)
at android.widget.ListView.dispatchDraw(ListView.java:3467)
at android.view.View.draw(View.java:17337)
at android.widget.AbsListView.draw(AbsListView.java:4704)
at android.view.View.updateDisplayListIfDirty(View.java:16264)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3874)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3854)
at android.view.View.updateDisplayListIfDirty(View.java:16218)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3874)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3854)
at android.view.View.updateDisplayListIfDirty(View.java:16218)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3874)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3854)
at android.view.View.updateDisplayListIfDirty(View.java:16218)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3874)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3854)
at android.view.View.updateDisplayListIfDirty(View.java:16218)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3874)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3854)
at android.view.View.updateDisplayListIfDirty(View.java:16218)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3874)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3854)
at android.view.View.updateDisplayListIfDirty(View.java:16218)
at android.view.ThreadedRenderer.updateViewTreeDisplayList(ThreadedRenderer.java:661)
at android.view.ThreadedRenderer.updateRootDisplayList(ThreadedRenderer.java:667)
at android.view.ThreadedRenderer.draw(ThreadedRenderer.java:775)
at android.view.ViewRootImpl.draw(ViewRootImpl.java:3188)
at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:2981)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2569)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1462)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6965)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:907)
at android.view.Choreographer.doCallbacks(Choreographer.java:709)
at android.view.Choreographer.doFrame(Choreographer.java:644)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:893)
at android.os.Handler.handleCallback(Handler.java:836)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:203)
at android.app.ActivityThread.main(ActivityThread.java:6251)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1075)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936)
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();
}
}
Filtering the text is working fine but now my requirement is to highlight the filtered text with some colour.How to implement this in my code
The code goes like this:
The filter method which is in the adapter class:
public class StudentAdapter extends RecyclerView.Adapter<StudentAdapter.ContestHolder> implements View.OnClickListener {
List<Student_model> data = new ArrayList<>();
List<Student_model> templist;
int expandedPosition = -1;
int prev = -2;
Context context;
student_fragment student_fragment;
Student_model contest;
String url = "http://labsls.com/drill/index.php/questionpool/deleteusers";
public class ContestHolder extends RecyclerView.ViewHolder {
public TextView title, sub, school, name, password, username, email, phonenum, stdlvl, std, scl;
public RelativeLayout details, titlebar;
public Button update, home;
public ImageView image, tick;
EditText stdnmedi, useredi, passwordedi, emailedi, phoneedi, stndrdedi, schooledi;
public ContestHolder(View v) {
super(v);
title = (TextView) v.findViewById(R.id.studenttitle);
sub = (TextView) v.findViewById(R.id.standardsub);
std = (TextView) v.findViewById(R.id.std);
scl = (TextView) v.findViewById(R.id.skool);
home = (Button) v.findViewById(R.id.homebt);
details = (RelativeLayout) v.findViewById(R.id.detials);
titlebar = (RelativeLayout) v.findViewById(R.id.titlebar);
name = (TextView) v.findViewById(R.id.stdname);
stdnmedi = (EditText) v.findViewById(R.id.namedi);
useredi = (EditText) v.findViewById(R.id.ediuser);
update = (Button) v.findViewById(R.id.updatebt);
passwordedi = (EditText) v.findViewById(R.id.passuser);
emailedi = (EditText) v.findViewById(R.id.ediemail);
phoneedi = (EditText) v.findViewById(R.id.ediphone);
stndrdedi = (EditText) v.findViewById(R.id.edistd);
schooledi = (EditText) v.findViewById(R.id.edischoolz);
tick = (ImageView) v.findViewById(R.id.imgtic);
}
}
public StudentAdapter(Context context, List<Student_model> data, student_fragment student) {
this.context = context;
this.data = data;
this.student_fragment = student;
this.templist = new ArrayList<>(data);
}
#Override
public ContestHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.student_list, parent, false);
ContestHolder holder = new ContestHolder(v);
holder.titlebar.setOnClickListener(StudentAdapter.this);
holder.titlebar.setTag(holder);
return holder;
}
#Override
public void onBindViewHolder(final ContestHolder holder, final int position) {
contest = data.get(position);
holder.title.setText(contest.getTitle());
holder.std.setText(" " + contest.getStdlevel());
holder.scl.setText(" " + contest.getSchool());
holder.stdnmedi.setText(contest.getTitle());
holder.useredi.setText(contest.getUsername());
holder.phoneedi.setText(contest.getPhonenum());
holder.passwordedi.setText(contest.getPassword());
holder.emailedi.setText(contest.getEmail());
holder.stndrdedi.setText(contest.getStdlevel());
holder.schooledi.setText(contest.getSchool());
holder.home.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
context.startActivity(new Intent(context, Landing.class));
}
});
holder.titlebar.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
data.get(position).setSelect(!data.get(position).isSelect());
holder.tick.setVisibility(data.get(position).isSelect() ? View.VISIBLE : View.GONE);
showremove();
return true;
}
});
holder.update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String ur = "http://labsls.com/drill/index.php/questionpool/updateuserdetails";
StringRequest stringrequest = new StringRequest(Request.Method.POST, ur, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("testup", response);
try {
JSONObject object = new JSONObject(response);
JSONArray array = object.getJSONArray("response");
for (int i = 0; i < array.length(); i++) {
JSONObject Objectz = array.getJSONObject(i);
String namee = Objectz.getString("fullname");
holder.stdnmedi.setText(namee);
String usere = Objectz.getString("username");
holder.useredi.setText(usere);
String passe = Objectz.getString("password");
holder.passwordedi.setText(passe);
String emaile = Objectz.getString("email_id");
holder.emailedi.setText(emaile);
String phonee = Objectz.getString("mobile");
holder.phoneedi.setText(phonee);
String stlvle = Objectz.getString("standardlevel");
holder.stndrdedi.setText(stlvle);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, error.toString(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
// params.put("nAme",holder.stdnmedi.getText().toString());
params.put("uName", holder.useredi.getText().toString());
params.put("pAwd", holder.passwordedi.getText().toString());
// params.put("eMail",holder.emailedi.getText().toString());
params.put("mobile", holder.phoneedi.getText().toString());
params.put("school", holder.schooledi.getText().toString());
params.put("standardlevel", holder.stndrdedi.getText().toString());
params.put("uID", contest.getUseruniq());
return params;
}
};
stringrequest.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(stringrequest);
Toast.makeText(context, holder.stdnmedi.getText().toString(), Toast.LENGTH_SHORT).show();
}
});
if (position == expandedPosition) {
holder.details.setVisibility(View.VISIBLE);
} else {
holder.details.setVisibility(View.GONE);
}
}
public void filter(String query) {
data.clear();
Log.d("Test", "1");
if (query.length() == 0) {
data.addAll(templist);
} else {
String filterPattern = query.toLowerCase().trim();
for (Student_model app : templist) {
if (app.getTitle().toLowerCase().contains(filterPattern)) {
data.add(app);
}
}
notifyDataSetChanged();
}
}
The class in which the filter method in the adapter class is being called:
SearchView.OnQueryTextListener listener = new SearchView.OnQueryTextListener(){
#Override
public boolean onQueryTextSubmit(String query){
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.filter(newText);
return true;
}
};
1. in StudentAdapter create global variable;
String searchString="";
2. in method filter(String query), asign searchString=query;
3. in onBindViewHolder() method, put below code.
SpannableString spannableStringSearch = null;
if ((searchString!= null) && (!searchString.isEmpty())) {
spannableStringSearch = new SpannableString(contest.getTitle());
Pattern pattern = Pattern.compile(searchString, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(contest.getTitle());
while (matcher.find()) {
spannableStringSearch.setSpan(new ForegroundColorSpan(
ContextCompat.getColor(context, R.color.red)),
matcher.start(), matcher.end(),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
if(spannableStringSearch !=null){
holder.title.setText(spannableStringSearch);
}
else{
holder.title.setText(spannableStringSearch);
}
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();
}
});