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
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);
}
}
This is the API
INPUT:
center_id:4
tabID:952888062222222
patient_search: 98
OUTPUT:
{
"status": true,
"result": [
{
"patient_id": "3",
"gen_patient_id": "pmhsola00003",
"first_name": "Sama",
"last_name": "Patil",
"p_mobile": "2398322323",
"aadhaar_number": "4561221211212",
"center_id": "4"
}
],
"message": "Patient searched successfully!"
}
Model Class
public class SearchModel {
public SearchModel(String patient_id, String gen_patient_id, String first_name, String last_name, String p_mobile, String aadhaar_number, String center_id) {
this.patient_id = patient_id;
this.gen_patient_id = gen_patient_id;
this.first_name = first_name;
this.last_name = last_name;
this.p_mobile = p_mobile;
this.aadhaar_number = aadhaar_number;
this.center_id = center_id;
}
private String patient_id;
public String getPatientId() { return this.patient_id; }
public void setPatientId(String patient_id) { this.patient_id = patient_id; }
private String gen_patient_id;
public String getGenPatientId() { return this.gen_patient_id; }
public void setGenPatientId(String gen_patient_id) { this.gen_patient_id = gen_patient_id; }
private String first_name;
public String getFirstName() { return this.first_name; }
public void setFirstName(String first_name) { this.first_name = first_name; }
private String last_name;
public String getLastName() { return this.last_name; }
public void setLastName(String last_name) { this.last_name = last_name; }
private String p_mobile;
public String getPMobile() { return this.p_mobile; }
public void setPMobile(String p_mobile) { this.p_mobile = p_mobile; }
private String aadhaar_number;
public String getAadhaarNumber() { return this.aadhaar_number; }
public void setAadhaarNumber(String aadhaar_number) { this.aadhaar_number = aadhaar_number; }
private String center_id;
public String getCenterId() { return this.center_id; }
public void setCenterId(String center_id) { this.center_id = center_id; }
#Override
public String toString()
{
return "ClassPojo [first_name = "+first_name+", aadhaar_number = "+aadhaar_number+", last_name = "+last_name+", patient_id = "+patient_id+", center_id = "+center_id+", p_mobile = "+p_mobile+", gen_patient_id = "+gen_patient_id+"]";
}
}
Result Model Class
public class Result {
private SearchModel[] result;
public SearchModel[] getResult() {
return result;
}
public void setResult(SearchModel[] result) {
this.result = result;
}
}
My Recycler Adapter
public class PatientSearchAdapter extends
RecyclerView.Adapter<PatientSearchAdapter.ViewHolder> {
private ArrayList<SearchModel> searchList;
private Context context;
public PatientSearchAdapter(ArrayList<SearchModel> searchList){
this.searchList = searchList;
}
#Override
public PatientSearchAdapter.ViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.search_list_row_new,parent,false);
PatientSearchAdapter.ViewHolder viewHolder = new PatientSearchAdapter.ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(PatientSearchAdapter.ViewHolder holder, final int position) {
holder.p_name_first.setText( (searchList.get(position).getFirstName()).substring(0,1).toUpperCase() + (searchList.get(position).getFirstName()).substring(1));
holder.p_name_last.setText( (searchList.get(position).getLastName()).substring(0,1).toUpperCase() + (searchList.get(position).getLastName()).substring(1));
holder.p_mobile.setText(searchList.get(position).getPMobile());
holder.p_Id.setText(searchList.get(position).getGenPatientId().toUpperCase());
holder.view_history.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(context, ViewPatientActivity.class);
context.startActivity(intent);
}
});
holder.take_test.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(context, HealthServicesActivity.class);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return searchList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView p_name_first,p_mobile,p_Id,p_name_last;
Button take_test;
TextView view_history;
public ViewHolder(View v) {
super(v);
p_name_first = (TextView) v.findViewById(R.id.ppatient_name);
p_name_last = (TextView) v.findViewById(R.id.ppatient_last_name);
p_mobile = (TextView) v.findViewById(R.id.pmobile_number);
p_Id=(TextView) v.findViewById(R.id.pp_id);
view_history=(TextView) v.findViewById(R.id.pview_text_1);
take_test=(Button) v.findViewById(R.id.ptake_test_button);
}
}
}
My Fragment
public class PatientListFragment extends Fragment implements
View.OnClickListener {
View view;
#BindView(R.id.search_text)
EditText searchText;
#BindView(R.id.item_search_click)
ImageButton saerchButton;
private ProgressBar progressBar;
Api webService = ServiceGenerator.getApi();
SharePreferenceManager<LoginModel> sharePreferenceManager;
private PatientSearchAdapter mSearchAdapter;
#BindView(R.id.recycler_patient_search_list)
RecyclerView recyclerViewOnSearch;
ArrayList<SearchModel> searchList = new ArrayList<SearchModel>();
public PatientListFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view= inflater.inflate(R.layout.fragment_patient_list, container, false);
ButterKnife.bind(this,view);
sharePreferenceManager = new SharePreferenceManager<>(getActivity());
progressBar =(ProgressBar) view.findViewById(R.id.progress_bar);
/* progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Please Wait...");
progressDialog.setCanceledOnTouchOutside(false);*/
EditText searchView = (EditText) view.findViewById(R.id.search_text);
initialViewsForSearch();
return view;
}
private void initialViewsForSearch() {
recyclerViewOnSearch.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerViewOnSearch.setLayoutManager(layoutManager);
#Override
public void onClick(View v) {
if (NetworkUtils.isNetworkAvailableToastIfNot(getActivity())) {
getPayientSearchListOnline(
sharePreferenceManager.getUserLoginData(LoginModel.class).getResult().getCenterId(),
sharePreferenceManager.getUserLoginData(LoginModel.class).getResult().getTabID(),
ComponentUtils.getInputStringFromView(searchText));
}
}
saerchButton.setOnClickListener(this);
}
/**
* Searching For Patient List
* #param centerId
* #param tabID
* #param searchtext
*/
private void getPayientSearchListOnline(String centerId, String tabID,String searchtext){
progressBar.setVisibility(View.VISIBLE);
Call<Result> profileModelCall = webService.getPatientSearchList(getMap(centerId,tabID,searchtext));
profileModelCall.enqueue(new Callback<Result>() {
#Override
public void onResponse(Call<Result> call, Response<Result> response) {
if (response.isSuccessful()) {
//if (response.body().isStatus()) {
recyclerView.setVisibility(View.GONE);
Result jsonResponse = response.body();
searchList = new ArrayList<>(Arrays.asList(jsonResponse.getResult()));
mSearchAdapter = new PatientSearchAdapter(searchList);
recyclerViewOnSearch.setAdapter(mSearchAdapter);
} else {
APIError apiError = ErrorUtils.parseError(response);
Toast.makeText(context, ""+ apiError.message(), Toast.LENGTH_SHORT).show();
}
if (progressBar.isEnabled())
progressBar.setVisibility(View.INVISIBLE);
progressBar.setVisibility(View.GONE);
}
#Override
public void onFailure(Call<Result> call, Throwable t) {
Toasty.error(getActivity(), "Please Try Again", Toast.LENGTH_SHORT, true).show();
if (progressBar.isEnabled())
progressBar.setVisibility(View.INVISIBLE);
progressBar.setVisibility(View.GONE);
}
});
}
/* *
* preparing Map data with param data
*/
private Map<String, RequestBody> getMap(String centerId, String tabId, String searchText) {
//All the String parameters, you have to put like
Map<String, RequestBody> map = new HashMap<>();
if (sharePreferenceManager != null && sharePreferenceManager.isUserLogin())
map.put("center_id", toRequestBody(centerId));
map.put("tabID", toRequestBody(tabId));
map.put("patient_search", toRequestBody(searchText));
return map;
}
/**
* This method converts String to RequestBody
*/
public static RequestBody toRequestBody(String value) {
return RequestBody.create(MediaType.parse("multipart/form-data"), value);
}
Api Call Interface
#Multipart
#POST(WebServices.GET_SEARCH_LIST)
Call<Result> getPatientSearchList(#PartMap Map<String, RequestBody> params);
what i am trying to do here is i am taking 1 edit text where i am putting number to enter , sending centerid,and tabID as parameter and for that i am doing Api Calling using Retrofit. but my problem is that whenever it goes to public void onResponse(Call call, Response response) {
it comes out from there and goes to failure and i am not getting the result after clicking the button.its showing me nothing .
I put a Recycler View into my fragment activity , which contains a number of Card View items
But when I click on the Refresh button, those items are created just for the first time
And when the Fragment is loaded for the next time, the items are not fetch again, and this is done only for the first time.
public class posts_fragment extends Fragment {
private List<PostData> PostDataList = new ArrayList<>();
PostDataAdapter adapter=new PostDataAdapter(PostDataList);
RecyclerView recyclerView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.posts_menu,container,false);
recyclerView =view.findViewById(R.id.PostRecycleView);
filldate();
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return view;
}
public void filldate() {
//Start Get And Set Json Into Card View
final String KeyUrl="http://www.rasamdev.ir/salehin/GetPost.php";
final String KeyUsername="Key";
StringRequest stringRequest = new StringRequest(Request.Method.POST, KeyUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(getContext(),response, Toast.LENGTH_SHORT).show();
//Start Pars
if (response != null) {
try {
JSONObject jObject = new JSONObject(response);
JSONArray array = jObject.getJSONArray("Posts");
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
String puid = object.getString("puid");
String Ptitr = object.getString("Ptitr");
String ptext = object.getString("ptext");
String pdate = object.getString("pdate");
String plike = object.getString("plike");
String pview = object.getString("pview");
String pimg = object.getString("pimg");
PostDataList.add(new PostData(pdate,ptext,puid,Ptitr,pimg,pview,plike));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
//End Pars
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), error + "", Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() {
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put(KeyUsername,"13581358r#R");
return hashMap;
}
};
RequestQueue requestQueue= Volley.newRequestQueue(this.getActivity());
requestQueue.add(stringRequest);
//End
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onResume() {
adapter.notifyDataSetChanged();
super.onResume();
}
Adapter Class :
public class PostDataAdapter extends RecyclerView.Adapter<PostDataAdapter.MyViewHolder> {
private List<PostData> PostDataList ;
public static class MyViewHolder extends RecyclerView.ViewHolder {
public TextView vPostContent, vPostDate, vPostAuthor, vPostTitr,VPostLikes,VPostViews;
public ImageView vPostPhoto;
public MyViewHolder(View v) {
super(v);
vPostContent = v.findViewById(R.id.PostContentTv);
vPostDate = v.findViewById(R.id.PostDateTv);
vPostAuthor = v.findViewById(R.id.PostAuthorTv);
vPostTitr = v.findViewById(R.id.PostTitrTv);
vPostPhoto = v.findViewById(R.id.PostPhoto);
VPostLikes=v.findViewById(R.id.PostLikeTv);
VPostViews=v.findViewById(R.id.PostViewTv);
}
}
public PostDataAdapter(List<PostData> postDataList) {
PostDataList = postDataList;
}
#Override
public PostDataAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_posts, parent, false);
MyViewHolder vh = new MyViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.vPostDate.setText(PostDataList.get(position).getPostDate());
holder.vPostTitr.setText(PostDataList.get(position).getPostTitr());
holder.vPostContent.setText(PostDataList.get(position).getPostContent());
holder.vPostAuthor.setText(PostDataList.get(position).getPostAuthor());
holder.VPostViews.setText(PostDataList.get(position).getPostViews());
holder.VPostLikes.setText(PostDataList.get(position).getPostLikes());
new DownloadImageTask(holder.vPostPhoto).execute(PostDataList.get(position).getImgpost());
}
#Override
public int getItemCount() {
return PostDataList.size();
}
}
Data Class :
public class PostData {
private String PostDate, PostContent, PostAuthor, PostTitr, imgpost, PostViews, PostLikes;
public PostData(String postDate, String postContent, String postAuthor, String postTitr, String imgpost, String postViews, String postLikes) {
PostDate = postDate;
PostContent = postContent;
PostAuthor = postAuthor;
PostTitr = postTitr;
this.imgpost = imgpost;
PostViews = postViews;
PostLikes = postLikes;
}
public String getPostDate() {
return PostDate;
}
public void setPostDate(String postDate) {
PostDate = postDate;
}
public String getPostContent() {
return PostContent;
}
public void setPostContent(String postContent) {
PostContent = postContent;
}
public String getPostAuthor() {
return PostAuthor;
}
public void setPostAuthor(String postAuthor) {
PostAuthor = postAuthor;
}
public String getPostTitr() {
return PostTitr;
}
public void setPostTitr(String postTitr) {
PostTitr = postTitr;
}
public String getImgpost() {
return imgpost;
}
public void setImgpost(String imgpost) {
this.imgpost = imgpost;
}
public String getPostViews() {
return PostViews;
}
public void setPostViews(String postViews) {
PostViews = postViews;
}
public String getPostLikes() {
return PostLikes;
}
public void setPostLikes(String postLikes) {
PostLikes = postLikes;
}
}
Hi I am new android developer i have stuck in my project. Problem is i want to user select items by checked box and after they click on view items button then open a another activity in which shows all those selected items in recyclerview in that recyclerview item name, price, and quantity.
This is my code
OderItems Activity, OderitemAdapter and OrderItemModel.
OderItems Activity
`public class OrderItems extends AppCompatActivity` {
public static final String KEY_ADSID="adsId";
public RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
recyclerView= (RecyclerView) findViewById(R.id.order_item_recyclerview);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(OrderItems.this,ViewOrder.class));
}
});
parseOrder();
}
public void parseOrder()
{
StringRequest stringRequest = new StringRequest(Request.Method.POST, Config.url_ORDERLISTING,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
Log.d("Response",jsonObject.toString());
if (jsonObject.optString("status").equalsIgnoreCase("1"))
{
// String no_task= jsonObject.getString("error_msg");
Toast.makeText(OrderItems.this,"No Order List List !",Toast.LENGTH_LONG).show();
// txt_noTask.setText("No Task Is Available");
// progressDialog.dismiss();
}
if (jsonObject.optString("status").equalsIgnoreCase("0") || jsonObject.optString("message").equalsIgnoreCase("Success"))
{
// Toast.makeText(getActivity(),jsonObject.toString(),Toast.LENGTH_LONG).show();
JSONArray jsonArray= jsonObject.getJSONArray("ItemList");
ArrayList<OrderItemModel> list =new ArrayList<>();
for (int i=0;i<jsonArray.length();i++)
{
// TodayTaskModel todayTask = new TodayTaskModel();
OrderItemModel orderitemmodel = new OrderItemModel();
JSONObject jsonObj= jsonArray.getJSONObject(i);
String product_Name =jsonObj.getString("productName");
String product_Price =jsonObj.getString("productPrice");
String package_img =jsonObj.getString("productImg");
// For Set data
orderitemmodel.setProductName(product_Name);
orderitemmodel.setProductPrice(product_Price);
orderitemmodel.setProductImg(package_img);
list.add(orderitemmodel);
}
// Setup and Handover data to recyclerview
OrderItemAdapter adapter=new OrderItemAdapter(getApplicationContext(),list);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
recyclerView.setHasFixedSize(true);
}
} catch (JSONException e) {
e.printStackTrace();
}
//pDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(OrderItems.this,"Server is not Responding !!! ", Toast.LENGTH_LONG).show();
// Toast.makeText(SpamActivity.this,error.toString(),Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put(KEY_ADSID,"101");
return params;
}
};
RequestQueue requestQueue =
Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
}
OderitemAdapter
public class OrderItemAdapter extends RecyclerView.Adapter<OrderItemAdapter.ViewHolder> {
ArrayList<OrderItemModel> orderItemList;
Context context;
SqlHandler sqlHandler;
static double summ;
public OrderItemAdapter(Context c, ArrayList<OrderItemModel> orderItemList)
{
this.context=c;
this.orderItemList=orderItemList;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.order_item_layout, parent, false);
sqlHandler = new SqlHandler(context);
return new OrderItemAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int i) {
final OrderItemModel position=orderItemList.get(i);
holder.txt_ProductName.setText(position.getProductName());
holder.txt_ProductPrice.setText(position.getProductPrice());
holder.urlProductImg=position.getProductImg();
holder.strRate = position.getProductPrice();
holder.strQuantity=position.getProductQty();
if (holder.urlProductImg.isEmpty()) { //url.isEmpty()
Picasso.with(context)
.load(R.drawable.localbizlist)
.placeholder(R.drawable.localbizlist)
.error(R.drawable.localbizlist)
.into(holder.img_product);
}else{
Picasso.with(context)
.load(orderItemList.get(i).getProductImg())
.placeholder(R.drawable.localbizlist)
.error(R.drawable.localbizlist)
.into(holder.img_product); //this is your ImageView
}
}
#Override
public int getItemCount() {
return orderItemList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
CheckBox chkOrder;
ImageView img_product;
TextView txt_ProductName,txt_ProductPrice;
Spinner itemSpinner;
String urlProductImg,strRate,strQuantity,strProductName;
public ViewHolder(View itemView) {
super(itemView);
context = itemView.getContext();
img_product=(ImageView)itemView.findViewById(R.id.img_product);
txt_ProductName=(TextView)itemView.findViewById(R.id.productName);
txt_ProductPrice=(TextView)itemView.findViewById(R.id.productPrice);
chkOrder=(CheckBox)itemView.findViewById(R.id.chk_order_status);
itemSpinner = (Spinner)itemView.findViewById(R.id.item_spinner);
List<String> itemQuuantity=new ArrayList<String>();
itemQuuantity.add("1");
itemQuuantity.add("2");
itemQuuantity.add("3");
itemQuuantity.add("4");
itemQuuantity.add("5");
ArrayAdapter<String> itemAdapter=new ArrayAdapter<String>(context,android.R.layout.simple_spinner_dropdown_item,itemQuuantity);
itemAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
itemSpinner.setAdapter(itemAdapter);
chkOrder.setOnClickListener(this);
}
#Override
public void onClick(View view) {
context = view.getContext();
double TotalBill=0.00;
if (view.getId()==chkOrder.getId())
{
if (chkOrder.isChecked())
{
double spQuantity = Double.parseDouble(itemSpinner.getSelectedItem().toString());
double itemRate = Double.parseDouble(strRate);
double itemPrice = (spQuantity * itemRate);
TotalBill+=itemPrice;
String strQuatity=Double.toString(spQuantity);
String strTotalBill = Double.toString(TotalBill);
String strProductName= String.valueOf(txt_ProductName.getText());
String strProductPrice=String.valueOf(txt_ProductPrice.getText());
Toast.makeText(context,"Checked Item Bill"+TotalBill,Toast.LENGTH_LONG).show();
String query = "INSERT INTO ORDER_ITEMS(product_name,product_quantity,product_price) values ('"
+ strProductName + "','" + strProductPrice + "','"+strQuatity+"')";
sqlHandler.executeQuery(query);
SumOrderBill(TotalBill);
Toast.makeText(context,"Record Save",Toast.LENGTH_LONG).show();
// showlist();
// strIDCheckBoxStatus=String.valueOf(chkOrder.getId());
}else
{
//saveInSp("Checked",false);
double spQuantity = Double.parseDouble(itemSpinner.getSelectedItem().toString());
double itemRate = Double.parseDouble(strRate);
double itemPrice = (spQuantity * itemRate);
TotalBill+=itemPrice;
String strIdProductName= String.valueOf(txt_ProductName.getText());
Toast.makeText(context,"UNCHECKED Item Bill"+TotalBill,Toast.LENGTH_LONG).show();
MinOrderBill(TotalBill);
String delQuery = "DELETE FROM PHONE_CONTACTS WHERE slno='"+strIdProductName+"' ";
sqlHandler.executeQuery(delQuery);
// showlist();
}
}
}
public void SumOrderBill(double ftotal)
{
summ+=ftotal;
String total2 = String.valueOf(summ);
Toast.makeText(context, "Total Bill"+total2,Toast.LENGTH_LONG).show();
// SharedPreferences myPrefsLogin=context.getSharedPreferences("biling", Context.MODE_PRIVATE);
// SharedPreferences.Editor editor = myPrefsLogin.edit();
// editor.putString("Total", total2);
// editor.commit();
}
public void MinOrderBill(double ftotal)
{
summ-=ftotal;
String total2 = String.valueOf(summ);
Toast.makeText(context, "Detection"+summ,Toast.LENGTH_LONG).show();
// SharedPreferences myPrefsLogin=context.getSharedPreferences("biling", Context.MODE_PRIVATE);
// SharedPreferences.Editor editor = myPrefsLogin.edit();
// editor.putString("Total", total2);
// editor.commit();
}
}
}
public class OrderItemModel {
private String status;
private String message;
private String productId;
private String productName;
private String productType;
private String productQty;
private String productImg;
private String productPrice;
public OrderItemModel()
{
}
public String getProductPrice() {
return productPrice;
}
public void setProductPrice(String productPrice) {
this.productPrice = productPrice;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductType() {
return productType;
}
public void setProductType(String productType) {
this.productType = productType;
}
public String getProductQty() {
return productQty;
}
public void setProductQty(String productQty) {
this.productQty = productQty;
}
public String getProductImg() {
return productImg;
}
public void setProductImg(String productImg) {
this.productImg = productImg;
}
}
Please help me for ViewOrder Activity
Here I am posting my code. After selecting checkbox user click on save button and onClick of that, another activity is open with only selected items(As you want),
Here is my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.rView);
context = this;
numberlist = new ArrayList<Number>();
for (int i = 0; i < 50; i++) {
Number number = new Number(String.valueOf(i), false);
number.setSelected(false);
numberlist.add(number);
}
customAdapter = new CustomAdapter(context, R.layout.list_item, numberlist);
recyclerView.setAdapter(customAdapter);
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
numberlist= customAdapter.onItemSelected();
customAdapter.setList(numberlist);
}
});
Here is my adapter's code:
public class CustomAdapter extends BaseAdapter {
private ArrayList<Number> numList;
Context context;
int textViewResourceId;
public CustomAdapter(Context context, int textViewResourceId, ArrayList<Number> numberlist) {
this.numList = new ArrayList<Number>();
this.numList.addAll(numberlist);
this.context=context;
this.textViewResourceId=textViewResourceId;
}
#Override
public int getCount() {
return numList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public class ViewHolder {
TextView code;
CheckBox name;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null) {
convertView=LayoutInflater.from(context).inflate(textViewResourceId,null);
holder = new ViewHolder();
convertView.findViewById(R.id.code);
holder.name = (CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder);
holder.name.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
Number number = (Number) cb.getTag();
number.setSelected(cb.isChecked());
}
});
} else {
holder = (ViewHolder) convertView.getTag();
}
Number number = numList.get(position);
holder.name.setText(number.getName());
holder.name.setChecked(number.isSelected());
holder.name.setTag(number);
if(number.isSelect()){
holder.name.setVisibility(View.GONE);
}
else {
holder.name.setVisibility(View.VISIBLE);
}
return convertView;
}
public ArrayList<Number> onItemSelected() {
StringBuffer text = new StringBuffer();
ArrayList<Number> numberArrayList=new ArrayList<Number>();
text.append("following are selected...\n");
for (int i = 0; i < numList.size(); i++) {
Number item = numList.get(i);
if (item.isSelected()) {
numList.get(i).setSelect(true);
numberArrayList.add(numList.get(i));
text.append("\n" + item.getName());
}
}
Log.e("Text ", text.toString());
return numberArrayList;
}
public void setList(ArrayList<Number> list){
numList.clear();
numList.addAll(list);
notifyDataSetChanged();
}
}
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);