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();
}
});
Related
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();
}
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();
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I want display Review text and its Rating in another activity.
Here is my AddReview class
public class AddReview extends AppCompatActivity implements ServerRequests.AddReviewreponse {
private Button submit;
EditText addReview;
RatingBar ratingBar;
Toolbar toolbar;
ServerRequests serverRequests;
JSONParser jsonParser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_review);
jsonParser = new JSONParser();
serverRequests = new ServerRequests(getApplicationContext());
serverRequests.setAddReviewreponse(this);
addReview=(EditText)findViewById(R.id.reviewBox);
ratingBar=(RatingBar) findViewById(R.id.ratingBar);
submit=(Button)findViewById(R.id.submit);
toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar_top);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Add Review");
// toolbar.setNavigationIcon(R.drawable.back_30);
/* toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});*/
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
String ReviewTxt = addReview.getText().toString();
float rating = ratingBar.getRating();
JSONObject obj = jsonParser.makeAddReviewJson(1,1,ReviewTxt,rating);
Log.e("final Json", obj.toString());
serverRequests.addReview(obj);
} catch (Exception e) {
}
/* Reviews.displayName.setText(RegisterActivity.name.getText().toString());
Reviews.displayReview.setText("Your Review : "+addReview.getText().toString());
Reviews.displayStars.setRating(ratingBar.getRating());*/
/* Reviews.displayStars.setText("Your Rating : " + ratingBar.getRating());
String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
Reviews.displayDate.setText(currentDateTimeString);*/
AlertDialog alertDialog = new AlertDialog.Builder(AddReview.this).create();
alertDialog.setTitle("Review Submitted!");
alertDialog.setMessage("Thanks for your valueable review!");
alertDialog.setIcon(R.drawable.star_48);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog closed
Toast.makeText(getApplicationContext(), "You clicked on OK", Toast.LENGTH_SHORT).show();
// startActivity(new Intent(getApplicationContext(), Reviews.class));
}
});
// Showing Alert Message
alertDialog.show();
}
});
}
#Override
public void onAddReviewReposne(JSONObject object) {
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==android.R.id.home)
{
finish();
}
return super.onOptionsItemSelected(item);
}
}
This is the Review class where I want to display the review and its ratings
public class Reviews extends AppCompatActivity implements ServerRequests.GetReviewResponse {
public static TextView displayReview, displayDate, displayName;
public static RatingBar displayStars;
Button addReviewBtn;
android.support.v7.widget.Toolbar toolbar;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private static String LOG_TAG = "CardViewActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reviews);
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view1);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
// mAdapter = new ReviewAdapter(getDataSet(jsonObject));
mRecyclerView.setAdapter(mAdapter);
toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar_top1);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Reviews");
/*displayReview = (TextView) findViewById(R.id.review);
displayStars = (RatingBar) findViewById(R.id.rating);
displayDate = (TextView)findViewById(R.id.displayDate);
displayName = (TextView)findViewById(R.id.displayName);*/
addReviewBtn = (Button)findViewById(R.id.addReviewBtn);
addReviewBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getApplicationContext(), AddReview.class));
}
});
ServerRequests serverRequests=new ServerRequests(getApplicationContext());
serverRequests.setReviewResponse(this);
serverRequests.getReviews("one");
}
private ArrayList<Review> getDataSet(JSONArray array) {
ArrayList results = new ArrayList<Review>();
for (int i = 0; i < array.length(); i++) {
try {
JSONObject object = array.getJSONObject(i);
Review obj = new Review(object.getInt("reviewId"),object.getInt("userId"),object.getString("Name"),object.getString("Review"),object.getLong("rating"));
results.add(i,obj);
}
catch (Exception e){
e.printStackTrace();
}
}
return results;
}
#Override
public void onGetReviewResponse(JSONArray jsonObject) {
mAdapter = new ReviewAdapter(getDataSet(jsonObject));
mRecyclerView.setAdapter(mAdapter);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==android.R.id.home)
{
finish();
}
return super.onOptionsItemSelected(item);
}
}
This is the ReviewAdapter
public class ReviewAdapter extends RecyclerView.Adapter<ReviewAdapter.DataObjectHolder> {
private static String LOG_TAG = "MyRecyclerViewAdapter";
private ArrayList<Review> mDataset;
private static MyClickListener myClickListener;
public static class DataObjectHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public static TextView name,review;
public static RatingBar rating;
public DataObjectHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.name);
review = (TextView) itemView.findViewById(R.id.review);
rating = (RatingBar) itemView.findViewById(R.id.rating);
Log.i(LOG_TAG, "Adding Listener");
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
myClickListener.onItemClick(getAdapterPosition(), v);
}
}
public void setOnItemClickListener(MyClickListener myClickListener) {
this.myClickListener = myClickListener;
}
public ReviewAdapter(ArrayList<Review> myDataset) {
mDataset = myDataset;
}
#Override
public DataObjectHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_view_review, parent, false);
DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
return dataObjectHolder;
}
#Override
public void onBindViewHolder(DataObjectHolder holder, int position) {
holder.name.setText(mDataset.get(position).getName());
holder.review.setText(mDataset.get(position).getReview());
holder.rating.setRating(mDataset.get(position).getRating());
}
public void addItem(Review dataObj, int index) {
mDataset.add(index, dataObj);
notifyItemInserted(index);
}
public void deleteItem(int index) {
mDataset.remove(index);
notifyItemRemoved(index);
}
#Override
public int getItemCount() {
return mDataset.size();
}
public interface MyClickListener {
public void onItemClick(int position, View v);
}
}
This is the Pojo class of Review
public class Review {
private String name,review;
private float rating;
private int reviewId,userId;
public Review (int ReviewId, int UserId, String Name, String Review, float Rating){
reviewId = ReviewId;
userId = UserId;
name = Name;
review = Review;
rating = Rating;
}
public int getReviewId() {
return reviewId;
}
public void setReviewId(int reviewId) {
this.reviewId = reviewId;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getReview() {
return review;
}
public void setReview(String review) {
this.review = review;
}
public float getRating() {
return rating;
}
public void setRating(float rating) {
this.rating = rating;
}
}
This is the ServerRequests for add and get Review
//------------For add review------------------------------
public void setAddReviewreponse(AddReviewreponse addreviewreponse) {
this.addreviewreponse = addreviewreponse;
}
private AddReviewreponse addreviewreponse;
public interface AddReviewreponse {
void onAddReviewReposne(JSONObject object);
}
public void addReview(JSONObject jsonObject) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, Services.ADD_REVIEW, jsonObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.e("Json response", "" + response);
boolean b = response.getBoolean("success");
if (addreviewreponse != null) {
addreviewreponse.onAddReviewReposne(response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error ", "" + error);
}
}
);
queue.add(jsonObjectRequest);
}
//------------For get review------------------------------
public void setReviewResponse(GetReviewResponse reviewResponse) {
this.getReviewResponse = reviewResponse;
}
public GetReviewResponse getReviewResponse;
public interface GetReviewResponse {
void onGetReviewResponse(JSONArray jsonObject);
}
public void getReviews(final String id) {
StringRequest request = new StringRequest(Request.Method.GET, Services.GET_REVIEW,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray array = new JSONArray(response);
Log.e("Server response", response);
if (array.length() > 0) {
if (getReviewResponse != null) {
getReviewResponse.onGetReviewResponse(array);
}
} else {
Log.e("Error is occured", "asd");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//send error repsonse back to user
Log.e("Error: ", error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<>();
params.put("courseId", id);
return params;
}
};
queue.add(request);
}
This is JSONParser class for AddReview
//--------For Add review---------------------------------
public JSONObject makeAddReviewJson(int studentID, int courseID, String reviewTxt, float rating) throws JSONException {
JSONObject object = new JSONObject();
object.put("studentId", studentID);
object.put("courseId", courseID);
object.put("review", reviewTxt);
object.put("ratings", rating);
return object;
}
This is the JSON response I am getting after posting the Review
E/final Json: {"studentId":1,"courseId":1,"review":"Hellooooo","ratings":3}
E/Json response: {"success":true,"msg":"Your review has been added successfully","data":{"reviewsId":18}}
private ArrayList<Review> getDataSet(JSONArray array) {
ArrayList results = new ArrayList<Review>();
for (int i = 0; i < array.length(); i++) {
try {
JSONObject object = array.getJSONObject(i);
Review obj = new Review(object.getInt("studentId"),object.getInt("courseId"),object.getString("Review"),object.getLong("rating"));
results.add(i,obj);
}
catch (Exception e){
e.printStackTrace();
}
}
return results;
}
try to change your getDataSet function with above code and check with debug point if you get any problem in some line. feel free to ask further will help you
EDIT:
You need to change your Pojo class of Review also. Because in JSON response you are not getting userId and reviewId. Hope you understand
I am trying to load data into my recyclerview via url okhttp calls, and I am receiving the following error:
"java.lang.ClassCastException: SearchActivity cannot be cast to SearchForBarbershop$BarbershopRequesterResponse"
Here are the classes.
SearchActivity:
public class SearchActivity extends AppCompatActivity {
private RecyclerAdapter mAdapter;
private RecyclerView mRecyclerView;
private LinearLayoutManager mLinearLayoutManager;
private ArrayList<Barbershop> barbershopList;
private SearchForBarbershop searchForBarbershop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
mLinearLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLinearLayoutManager);
barbershopList = new ArrayList<>();
mAdapter = new RecyclerAdapter(barbershopList);
mRecyclerView.setAdapter(mAdapter);
setRecyclerViewScrollListener();
searchForBarbershop = new SearchForBarbershop(this);
}
#Override
protected void onStart() {
super.onStart();
if (barbershopList.size() == 0) {
requestShop();
}
}
private int getLastVisibleItemPosition() {
return mLinearLayoutManager.findLastVisibleItemPosition();
}
private void setRecyclerViewScrollListener() {
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
int totalItemCount = mRecyclerView.getLayoutManager().getItemCount();
if (!searchForBarbershop.isLoadingData() && totalItemCount == getLastVisibleItemPosition() + 1) {
requestShop();
}
}
});
}
private void requestShop() {
try {
searchForBarbershop.getBarbershop();
} catch (IOException e) {
e.printStackTrace();
}
}
//#Override
public void receivedNewShop(final Barbershop newBarbershop) {
runOnUiThread(new Runnable() {
#Override
public void run() {
barbershopList.add(newBarbershop);
mAdapter.notifyItemInserted(barbershopList.size());
}
});
}
}
SearchForBarbershop:
public class SearchForBarbershop {
public interface BarbershopRequesterResponse {
void receivedNewBarbershop(Barbershop barbershop);
}
private BarbershopRequesterResponse barbershopRequesterResponse;
private OkHttpClient client;
private boolean isLoadingData;
public boolean isLoadingData() { return isLoadingData; }
public SearchForBarbershop (Activity listeningActivity) {
client = new OkHttpClient();
isLoadingData = false;
barbershopRequesterResponse = (BarbershopRequesterResponse) listeningActivity;
}
public void getBarbershop() throws IOException {
String url = "http://pubapi.yp.com/search-api/search/devapi/search?searchloc=30043&term=barbers&format=json&sort=distance&radius=50&listingcount=20&key=gmj3x7mhsh";
Request request = new Request.Builder().url(url).build();
isLoadingData = true;
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
isLoadingData = false;
e.printStackTrace();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
try {
JSONObject object = new JSONObject(response.body().string());
Barbershop receivedShop = new Barbershop(object);
barbershopRequesterResponse.receivedNewBarbershop(receivedShop);
isLoadingData = false;
} catch (JSONException e) {
isLoadingData = false;
e.printStackTrace();
}
}
});
}
}
Barbershop:
public class Barbershop{
private String name;
private String city;
public Barbershop(JSONObject barbershopJSON) {
try {
JSONArray businessArray = barbershopJSON.getJSONObject("searchResult").getJSONObject("searchListings").getJSONArray("searchListing");
for(int i = 0; i < businessArray.length(); i++) {
//Parse JSON and assign to variables
JSONObject business_object_1 = businessArray.getJSONObject(i);
String primaryc = business_object_1.getString("primaryCategory");
//Check to make sure the main category is "Barbers"
if((primaryc).equals("Barbers")) {
name = business_object_1.getString("businessName");
city = business_object_1.getString("city");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public String getCity() {
return city;
}
public String getName() {
return name;
}
}
RecyclerAdapter:
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ShopHolder> {
private ArrayList<Barbershop> mbarbershops;
public RecyclerAdapter(ArrayList<Barbershop> barbershops) {
mbarbershops = barbershops;
}
#Override
public RecyclerAdapter.ShopHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View inflatedView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.cardview_barber_search, parent, false);
return new ShopHolder(inflatedView);
}
#Override
public void onBindViewHolder(RecyclerAdapter.ShopHolder holder, int position) {
Barbershop itemBarbershop = mbarbershops.get(position);
holder.bindShop(itemBarbershop);
}
#Override
public int getItemCount() {
return 0;
}
public static class ShopHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView mName;
private TextView mCity;
public ShopHolder(View view) {
super(view);
mName = (TextView) view.findViewById(R.id.textViewName);
mCity = (TextView) view.findViewById(R.id.textViewCity);
view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
}
public void bindShop(Barbershop barbershop) {
mName.setText(barbershop.getName());
mCity.setText(barbershop.getCity());
}
}
}
It can't be cast because it doesn't implement that interface. Your commented-out #override statement should be a clue for you here.
Change it to:
public class SearchActivity extends AppCompatActivity
implements SearchForBarbershop.BarbershopRequesterResponse {
....
And don't forget to remove the comment for method you implemented:
#Override
public void receivedNewShop(final Barbershop newBarbershop) {
....
I think you need change constructor SearchForBarbershop
BarbershopRequesterResponse listener;
Context context
public SearchForBarbershop (Context context,BarbershopRequesterResponse listener) {
client = new OkHttpClient();
isLoadingData = false;
this.context = context;
this.listener = listener;
}
And change in SearchActivity
searchForBarbershop = new SearchForBarbershop(SearchActivity.this, this);
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);