Retrofit2 Api Call Error not showing the Result in Recycler view - android

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 .

Related

data is not getting displayed in retrofit

I using retrofit to display data but data is not getting displayed.i don't know where am I getting wrong.in logcat im getting response as:
2019-12-26 20:34:39.847 28305-28305/com.example.androidtutorial E/helloash: [com.example.androidtutorial.GetAheadFolder.JavaDatum#36ebcd9]
I need help..thanks
GetAHeadModelsnext:
public class GetAHeadModelsnext{
#SerializedName("id")
#Expose
private String id;
#SerializedName("title")
#Expose
private String title;
#SerializedName("java_data")
#Expose
private List<JavaDatum> java_data ;
#SerializedName("xml_data")
#Expose
private List<XmlDatum> xmlData;
public GetAHeadModelsnext(String id, String title, List<JavaDatum> java_data, List<XmlDatum> xmlData) {
this.id = id;
this.title = title;
this.java_data = java_data;
this.xmlData = xmlData;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<JavaDatum> getJavaData() {
return java_data;
}
public void setJavaData(List<JavaDatum> javaData) {
this.java_data = javaData;
}
public List<XmlDatum> getXmlData() {
return xmlData;
}
public void setXmlData(List<XmlDatum> xmlData) {
this.xmlData = xmlData;
}
submodel(ListJavaDatum):
public class JavaDatum {
#SerializedName("file_name")
#Expose
private String fileName;
#SerializedName("code")
#Expose
private String code;
public JavaDatum(String fileName, String code) {
this.fileName = fileName;
this.code = code;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}}
interface:
public interface DescriptService {
#GET("/v1/android_tutorials/single_advance?")
Call<GetAHeadModelsnext> getaheadjava(#Query("advance_id") String id);}
activity:
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
/*Create handle for the RetrofitInstance interface*/
progressDialog = new ProgressDialog(getContext());
progressDialog.setMessage("Loading....");
progressDialog.show();
Intent intent = getActivity().getIntent();
String id = intent.getStringExtra("idGHnext");
Log.e("ashwiniiii", String.valueOf(id));
GetAheadApiService service = GetAheadApiClient.getRetrofitInstance().create(GetAheadApiService.class);
Call<GetAHeadModelsnext> call = service.getaheadjava(id);
call.enqueue(new Callback<GetAHeadModelsnext>() {
#Override
public void onResponse(Call<GetAHeadModelsnext> call, Response<GetAHeadModelsnext> response) {
progressDialog.dismiss();
List<JavaDatum> retro=response.body().getJavaData();
generateDataList(retro);
Log.e("helloash", String.valueOf(response.body().getJavaData()));
}
#Override
public void onFailure(Call<GetAHeadModelsnext> call, Throwable t) {
progressDialog.dismiss();
Toast.makeText(getContext(), "Something went wrong...Please try later!", Toast.LENGTH_SHORT).show();
}
});
}
private void generateDataList(List<JavaDatum> photoList) {
recyclerView = getView().findViewById(R.id.nextGHrecycle);
LinearLayoutManager manager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(manager);
recyclerView.setHasFixedSize(true);
adapter = new JavaGetAheadAdapter(getContext(),photoList);
recyclerView.setAdapter(adapter);
}}
ADapter:
public class JavaGetAheadAdapter extends RecyclerView.Adapter<JavaGetAheadAdapter.CustomViewHolder> {
List<JavaDatum> GHmdel;
Context context;
public JavaGetAheadAdapter(Context context,List<JavaDatum> employees) {
this.GHmdel = employees;
this.context = context;
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.getaheadnext_item, parent, false);
return new CustomViewHolder(itemView);
}
#Override
public void onBindViewHolder(CustomViewHolder holder, int position) {
holder.employeeName.setText(GHmdel.get(position).getFileName());//
holder.textView.setText(GHmdel.get(position).getCode());
Log.d("adapter",GHmdel.get(position).getFileName());
Log.d("adapter2",GHmdel.get(position).getCode());
}
#Override
public int getItemCount() {
return GHmdel.size();
}
public class CustomViewHolder extends RecyclerView.ViewHolder {
public TextView employeeName;
TextView textView;
public CustomViewHolder(View view) {
super(view);
employeeName = (TextView) view.findViewById(R.id.detailsgetaheadtitle);
textView = view.findViewById(R.id.detailsgetahead);}}}
my json :
{
"id": "1",
"title": "ViewPager and TabHost",
"java_data": [
{
"file_name": "ListDisplay.java",
"code": "package com.example.ListDisplay;\r\n\r\nimport android.os.Bundle;\r\nimport android.app.Activity;\r\nimport android.view.Menu;\r\nimport android.widget.ArrayAdapter;\r\nimport android.widget.ListView;\r\n\r\npublic class ListDisplay extends Activity {\r\n // Array of strings...\r\n String[] mobileArray = {\"Android\",\"IPhone\",\"WindowsMobile\",\"Blackberry\",\r\n \"WebOS\",\"Ubuntu\",\"Windows7\",\"Max OS X\"};\r\n \r\n #Override\r\n protected void onCreate(Bundle savedInstanceState) {\r\n super.onCreate(savedInstanceState);\r\n setContentView(R.layout.activity_main);\r\n \r\n ArrayAdapter adapter = new ArrayAdapter<String>(this, \r\n R.layout.activity_listview, mobileArray);\r\n \r\n ListView listView = (ListView) findViewById(R.id.mobile_list);\r\n listView.setAdapter(adapter);\r\n }\r\n}"
}
],
"xml_data": [
{
"file_name": "activity_main.xml",
"code": "<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\r\n xmlns:tools=\"http://schemas.android.com/tools\"\r\n android:layout_width=\"match_parent\"\r\n android:layout_height=\"match_parent\"\r\n android:orientation=\"vertical\"\r\n tools:context=\".ListActivity\" >\r\n\r\n <ListView\r\n android:id=\"#+id/mobile_list\"\r\n android:layout_width=\"match_parent\"\r\n android:layout_height=\"wrap_content\" >\r\n </ListView>\r\n \r\n</LinearLayout>\r\nimport android.os.Bundle;\r\nimport android.app.Activity;\r\nimport android.view.Menu;\r\nimport android.widget.ArrayAdapter;\r\nimport android.widget.ListView;\r\n\r\npublic class ListDisplay extends Activity {\r\n // Array of strings...\r\n String[] mobileArray = {\"Android\",\"IPhone\",\"WindowsMobile\",\"Blackberry\",\r\n \"WebOS\",\"Ubuntu\",\"Windows7\",\"Max OS X\"};\r\n \r\n #Override\r\n protected void onCreate(Bundle savedInstanceState) {\r\n super.onCreate(savedInstanceState);\r\n setContentView(R.layout.activity_main);\r\n \r\n ArrayAdapter adapter = new ArrayAdapter<String>(this, \r\n R.layout.activity_listview, mobileArray);\r\n \r\n ListView listView = (ListView) findViewById(R.id.mobile_list);\r\n listView.setAdapter(adapter);\r\n }\r\n}"
},
{
"file_name": "strings.xml",
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<resources>\r\n <string name=\"app_name\">ListDisplay</string>\r\n <string name=\"action_settings\">Settings</string>\r\n</resources>"
},
{
"file_name": "activity_listview.xml",
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<!-- Single List Item Design -->\r\n\r\n<TextView xmlns:android=\"http://schemas.android.com/apk/res/android\"\r\n android:id=\"#+id/label\"\r\n android:layout_width=\"fill_parent\"\r\n android:layout_height=\"fill_parent\"\r\n android:padding=\"10dip\"\r\n android:textSize=\"16dip\"\r\n android:textStyle=\"bold\" >\r\n</TextView>"
}
]
}
Might be i got the problem.
Problem is here #GET("/v1/android_tutorials/single_advance?") you have? in the end of your url and you also have #Query("advance_id") field that mean your request contain two ?. you request currently look like this.
/v1/android_tutorials/single_advance??advance_id="xxxx"
Remember when you add #Query("advance_id") to your request this by default add ? to your your. So remove? from your url end. Your url should look like this
#GET("/v1/android_tutorials/single_advance")
Try to remove / before v1 in your interface GET method and add that into your base url. In short in any method of retrofit interface don't start with /.
Assuming data is there try making below changes
public class JavaGetAheadAdapter extends RecyclerView.Adapter<JavaGetAheadAdapter.CustomViewHolder> {
List<JavaDatum> GHmdel = new ArrayList(); //new change
Context context;
//removed the list from constructor
public JavaGetAheadAdapter(Context context) {
this.GHmdel = employees;
}
//new method for updating the data items
public void updateData(List<JavaDatum> employees){
this.GHmdel.addAll(employees);
notifyDataSetChanged();
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.getaheadnext_item, parent, false);
return new CustomViewHolder(itemView);
}
#Override
public void onBindViewHolder(CustomViewHolder holder, int position) {
holder.employeeName.setText(GHmdel.get(position).getFileName());//
holder.textView.setText(GHmdel.get(position).getCode());
Log.d("adapter",GHmdel.get(position).getFileName());
Log.d("adapter2",GHmdel.get(position).getCode());
}
#Override
public int getItemCount() {
return GHmdel.size();
}
public class CustomViewHolder extends RecyclerView.ViewHolder {
public TextView employeeName;
TextView textView;
public CustomViewHolder(View view) {
super(view);
employeeName = (TextView) view.findViewById(R.id.detailsgetaheadtitle);
textView = view.findViewById(R.id.detailsgetahead);}}}
At the calling side just make the mentioned below changes.
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
/*Create handle for the RetrofitInstance interface*/
progressDialog = new ProgressDialog(getContext());
progressDialog.setMessage("Loading....");
progressDialog.show();
Intent intent = getActivity().getIntent();
String id = intent.getStringExtra("idGHnext");
Log.e("ashwiniiii", String.valueOf(id));
// new changes
generateDataList(view);
GetAheadApiService service = GetAheadApiClient.getRetrofitInstance().create(GetAheadApiService.class);
Call<GetAHeadModelsnext> call = service.getaheadjava(id);
call.enqueue(new Callback<GetAHeadModelsnext>() {
#Override
public void onResponse(Call<GetAHeadModelsnext> call, Response<GetAHeadModelsnext> response) {
progressDialog.dismiss();
List<JavaDatum> retro=response.body().getJavaData();
//new changes
adapter.updateData(retro);
Log.e("helloash", String.valueOf(response.body().getJavaData()));
}
#Override
public void onFailure(Call<GetAHeadModelsnext> call, Throwable t) {
progressDialog.dismiss();
Toast.makeText(getContext(), "Something went wrong...Please try later!", Toast.LENGTH_SHORT).show();
}
});
}
//new changes goes here
private void generateDataList(View view) {
recyclerView = view.findViewById(R.id.nextGHrecycle);
LinearLayoutManager manager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(manager);
recyclerView.setHasFixedSize(true);
adapter = new JavaGetAheadAdapter(getContext());
recyclerView.setAdapter(adapter);
}}
Try and comment below if its working or not still.

Update the RecyclerView adapter items in fragment

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;
}
}

RecyclerView (No adapter attached;skipping layout) using retrofit and fragment

Hi Im trying to show a list from retrofit onResponse and I am using recyclerview inside a fragment. The list shoud show chefs but I got an error from RecyclerView
Conexion Class
public class Conexion {
public static String BASE_URL = "http://10.30.0.133:8091/Service1.asmx/";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
EndPoint Interface
public interface EndPointsInterface {
#GET("chef/{idUser}")
Call<ChefResponse> GetChefsCercanos(#Path("idUser") Integer id_usuario);
}
Entity Usuario
public class Usuario {
#SerializedName("id_usuario")
private Integer id_usuario;
#SerializedName("NombreUsuario")
private String NombreUsuario;
#SerializedName("ApellidoUsuario")
private String ApellidoUsuario;
#SerializedName("TelefonoUsuario")
private String TelefonoUsuario;
#SerializedName("Email")
private String Email;
#SerializedName("Contraseña")
private String Contraseña;
#SerializedName("pos_x")
private Double pos_x;
#SerializedName("pos_y")
private Double pos_y;
public Usuario(){}
public Usuario(Integer id_usuario,String NombreUsuario,String ApellidoUsuario,String TelefonoUsuario,String Email,String Contraseña,Double pos_x,Double pos_y){
this.id_usuario=id_usuario;
this.NombreUsuario=NombreUsuario;
this.ApellidoUsuario=ApellidoUsuario;
this.TelefonoUsuario=TelefonoUsuario;
this.Contraseña=Contraseña;
this.pos_x=pos_x;
this.pos_y=pos_y;
}
public Integer getId_usuario() {
return id_usuario;
}
public void setId_usuario(Integer id_usuario) {
this.id_usuario = id_usuario;
}
public String getNombreUsuario() {
return NombreUsuario;
}
public void setNombreUsuario(String nombreUsuario) {
NombreUsuario = nombreUsuario;
}
public String getApellidoUsuario() {
return ApellidoUsuario;
}
public void setApellidoUsuario(String apellidoUsuario) {
ApellidoUsuario = apellidoUsuario;
}
public String getTelefonoUsuario() {
return TelefonoUsuario;
}
public void setTelefonoUsuario(String telefonoUsuario) {
TelefonoUsuario = telefonoUsuario;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public String getContraseña() {
return Contraseña;
}
public void setContraseña(String contraseña) {
Contraseña = contraseña;
}
public Double getPos_x() {
return pos_x;
}
public void setPos_x(Double pos_x) {
this.pos_x = pos_x;
}
public Double getPos_y() {
return pos_y;
}
public void setPos_y(Double pos_y) {
this.pos_y = pos_y;
}
}
Entity Chef
public class Chef extends Usuario{
#SerializedName("id_chef")
private Integer id_chef;
#SerializedName("TipoServicio")
private String TipoServicio;
#SerializedName("Rating")
private Double Rating;
#SerializedName("EstadoChef")
private Boolean EstadoChef;
public Chef(){}
public Chef(Integer id_usuario,String NombreUsuario,String ApellidoUsuario,String TelefonoUsuario,String Email,String Contraseña,Double pos_x,Double pos_y,Integer id_chef,String TipoServicio,Double Rating,Boolean EstadoChef){
super(id_usuario,NombreUsuario,ApellidoUsuario,TelefonoUsuario,Email,Contraseña,pos_x,pos_y);
this.id_chef=id_chef;
this.TipoServicio=TipoServicio;
this.Rating=Rating;
this.EstadoChef=EstadoChef;
}
public Integer getId_chef() {
return id_chef;
}
public void setId_chef(Integer id_chef) {
this.id_chef = id_chef;
}
public String getTipoServicio() {
return TipoServicio;
}
public void setTipoServicio(String tipoServicio) {
TipoServicio = tipoServicio;
}
public Double getRating() {
return Rating;
}
public void setRating(Double rating) {
Rating = rating;
}
public Boolean getEstadoChef() {
return EstadoChef;
}
public void setEstadoChef(Boolean estadoChef) {
EstadoChef = estadoChef;
}
}
Chef Response
public class ChefResponse {
#SerializedName("results")
private Chef[] results;
public Chef[] getresults(){
return results;
}
}
RecyclerView Adapter
public class ListaChefsCercanos extends RecyclerView.Adapter<ListaChefsCercanos.ListaChefsCercanosViewHolder> {
private List<Chef> chefs;
private List<Usuario> usuarios;
private int rowLayout;
private Context context;
#Override
public ListaChefsCercanosViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(rowLayout, parent, false);
return new ListaChefsCercanosViewHolder(view);
}
#Override
public void onBindViewHolder(ListaChefsCercanosViewHolder holder, int position) {
holder.nombreschefscerca.setText(chefs.get(position).getNombreUsuario());
holder.ratingchef.setText(chefs.get(position).getRating().toString());
}
#Override
public int getItemCount() {
return chefs.size();
}
public static class ListaChefsCercanosViewHolder extends RecyclerView.ViewHolder{
LinearLayout chefslayout;
TextView nombreschefscerca;
TextView ratingchef;
public ListaChefsCercanosViewHolder(View v){
super(v);
chefslayout=(LinearLayout) v.findViewById(R.id.cheflayoutcerca);
nombreschefscerca=(TextView) v.findViewById(R.id.tv_NombreChefCercano);
ratingchef=(TextView) v.findViewById(R.id.tv_RatingChefCercano);
}
}
public ListaChefsCercanos(ArrayList <Chef> chefs){
this.chefs=chefs;
//this.rowLayout = rowLayout;
//this.context = context;
}
}
and the fragment
public class RecomendadosFragment extends Fragment {
private RatingBar ratingBar;
//ListAdapter adapter;
ArrayList<Chef> listachef;
ListView lvLista;
String tag_json_array="jarray req";
RecyclerView recyclerviewChefsCarnos;
ListaChefsCercanos mListaChefsCercanos;
private ArrayList<Chef> data;
private ListaChefsCercanos adapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View x = inflater.inflate(R.layout.recomendados,null);
//ratingBar = (RatingBar) x.findViewById(R.id.rb_RatingChefCercano);
recyclerviewChefsCarnos=(RecyclerView) x.findViewById(R.id.rv_chefsCernaos);
recyclerviewChefsCarnos.setLayoutManager(new LinearLayoutManager(getActivity().getApplicationContext()));
EndPointsInterface apiService = Conexion.getClient().create(EndPointsInterface.class);
Call<ChefResponse> call = apiService.GetChefsCercanos(5);
call.enqueue(new Callback<ChefResponse>() {
#Override
public void onResponse(Call<ChefResponse> call, Response<ChefResponse> response) {
int statusCode = response.code();
if (response.isSuccessful()) {
ChefResponse jsonResponse = response.body();
if(jsonResponse != null) {
data = new ArrayList<>(Arrays.asList(jsonResponse.getresults()));
adapter= new ListaChefsCercanos(data);
recyclerviewChefsCarnos.setAdapter(adapter);
}
} else {
// Do whatever you want if API is unsuccessful.
}
// List<Chef> chefs= response.body().getResults();
// recyclerviewChefsCarnos.setAdapter(new ListaChefsCercanos( chefs,R.layout.itemchefscercanos,getActivity().getApplicationContext()));
}
#Override
public void onFailure(Call<ChefResponse> call, Throwable t) {
Log.d("Error",t.getMessage());
}
});
return x;
}
this is the error I found while Im debuging
E/RecyclerView: No adapter attached; skipping layout
Update: Use a empty adapter for the RecyclerView in the OncreateView()
recyclerView.setAdapter(new YourAdapter(getCurrentActivity()));

I want to display data from Json in recyclerview in Android [closed]

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

Android firebase query search title issue

This is SearchActivity.java
public class SearchActivity extends AppCompatActivity
{
/*UI*/
private EditText mSearchText;
private Button mSearchBtn;
private Toolbar mSearchToolbar;
private FragmentPagerAdapter mPagerAdapter;
private ViewPager mViewPager;
private String value;
private TextWatcher tw;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
mSearchText = (EditText)findViewById(R.id.activity_search_search_text);
mSearchBtn = (Button)findViewById(R.id.activity_search_search_btn);
mSearchToolbar = (Toolbar)findViewById(R.id.activity_search_toolbar);
setSupportActionBar(mSearchToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(null);
mSearchBtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
value = mSearchText.getText().toString();
Toast.makeText(SearchActivity.this, "value test 1: " + value, Toast.LENGTH_LONG).show();
searchText(value);
}
});
}
private void searchText(final String value)
{
Toast.makeText(SearchActivity.this, "value test 2: " + value, Toast.LENGTH_LONG).show();
mPagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager())
{
private final Fragment[] mFragments = new Fragment[]
{
new FragmentSearch(value)
};
#Override
public Fragment getItem(int position)
{
return mFragments[position];
}
#Override
public int getCount()
{
return mFragments.length;
}
};
mViewPager = (ViewPager) findViewById(R.id.activity_search_view_pager);
mViewPager.setAdapter(mPagerAdapter);
}
}
This is FragmentSearch.java
public class FragmentSearch extends MainFragment
{
public String value;
public FragmentSearch(String value)
{
this.value = value;
}
#Override
public Query getQuery(DatabaseReference databaseReference)
{
Toast.makeText(getActivity().this, "value test 3: " + value, Toast.LENGTH_LONG).show();
Query postsQuery = databaseReference.child("Post").orderByChild("title").equalTo(value);
return postsQuery;
}
}
This is MainFragment.java
public abstract class MainFragment extends Fragment
{
private DatabaseReference mDatabase;
private FirebaseRecyclerAdapter<Post, PostViewHolder> mAdapter;
private RecyclerView mRecycler;
private LinearLayoutManager mManager;
public MainFragment()
{
}
#Override
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
super.onCreateView(inflater, container, savedInstanceState);
View rootView = inflater.inflate(R.layout.fragment_all_posts, container, false);
mDatabase = FirebaseDatabase.getInstance().getReference();
mRecycler = (RecyclerView)rootView.findViewById(R.id.messages_list);
mRecycler.setHasFixedSize(true);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
mManager = new LinearLayoutManager(getActivity());
mManager.setReverseLayout(true);
mManager.setStackFromEnd(true);
mRecycler.setLayoutManager(mManager);
Query postsQuery = getQuery(mDatabase);
mAdapter = new FirebaseRecyclerAdapter<Post, PostViewHolder>(Post.class, R.layout.item_post,
PostViewHolder.class, postsQuery)
{
#Override
protected void populateViewHolder(final PostViewHolder viewHolder, final Post model, final int position)
{
final DatabaseReference postRef = getRef(position);
final String postKey = postRef.getKey();
viewHolder.itemView.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// Intent intent = new Intent(getActivity(), PostDetailActivity.class);
// intent.putExtra(PostDetailActivity.EXTRA_POST_KEY, postKey);
// startActivity(intent);
}
});
if(model.stars.containsKey(getUid()))
{
viewHolder.starView.setImageResource(R.drawable.ic_toggle_star_24);
}
else
{
viewHolder.starView.setImageResource(R.drawable.ic_toggle_star_outline_24);
}
viewHolder.bindToPost(model, new View.OnClickListener()
{
#Override
public void onClick(View starView)
{
DatabaseReference globalPostRef = mDatabase.child("Post").child(postRef.getKey());
DatabaseReference userPostRef = mDatabase.child("UserPost").child(model.uid).child(postRef.getKey());
onStarClicked(globalPostRef);
onStarClicked(userPostRef);
}
});
}
};
mRecycler.setAdapter(mAdapter);
}
private void onStarClicked(DatabaseReference postRef) {
postRef.runTransaction(new Transaction.Handler() {
#Override
public Transaction.Result doTransaction(MutableData mutableData) {
Post p = mutableData.getValue(Post.class);
if (p == null) {
return Transaction.success(mutableData);
}
if (p.stars.containsKey(getUid())) {
// Unstar the post and remove self from stars
p.starCount = p.starCount - 1;
p.stars.remove(getUid());
} else {
// Star the post and add self to stars
p.starCount = p.starCount + 1;
p.stars.put(getUid(), true);
}
// Set value and report transaction success
mutableData.setValue(p);
return Transaction.success(mutableData);
}
#Override
public void onComplete(DatabaseError databaseError, boolean b,
DataSnapshot dataSnapshot) {
}
});
}
#Override
public void onDestroy()
{
super.onDestroy();
if (mAdapter != null)
{
mAdapter.cleanup();
}
}
public String getUid()
{
return FirebaseAuth.getInstance().getCurrentUser().getUid();
}
public abstract Query getQuery(DatabaseReference databaseReference);
}
This is PostViewHolder.java
public class PostViewHolder extends RecyclerView.ViewHolder
{
public TextView titleView;
public TextView authorView;
public ImageView starView;
public TextView numStarsView;
public TextView bodyView;
public PostViewHolder(View itemView)
{
super(itemView);
titleView = (TextView) itemView.findViewById(R.id.post_title);
authorView = (TextView) itemView.findViewById(R.id.post_author);
starView = (ImageView) itemView.findViewById(R.id.star);
numStarsView = (TextView) itemView.findViewById(R.id.post_num_stars);
bodyView = (TextView) itemView.findViewById(R.id.post_body);
}
public void bindToPost(Post post, View.OnClickListener starClickListener)
{
titleView.setText(post.title);
authorView.setText(post.author);
numStarsView.setText(String.valueOf(post.starCount));
bodyView.setText(post.body);
starView.setOnClickListener(starClickListener);
}
}
This is Post.java
#IgnoreExtraProperties
public class Post
{
public String uid;
public String author;
public String title;
public String body;
public int starCount = 0;
public String type;
public Map<String, Boolean> stars = new HashMap<>();
public Post()
{
}
public Post(String uid, String author, String title, String body, String type)
{
this.uid = uid;
this.author = author;
this.title = title;
this.body = body;
this.type = type;
}
#Exclude
public Map<String, Object> toMap()
{
HashMap<String, Object> result = new HashMap<>();
result.put("uid", uid);
result.put("author", author);
result.put("title", title);
result.put("body", body);
result.put("starCount", starCount);
result.put("stars", stars);
result.put("type", type);
return result;
}
}
Thank you so much for reading. I created a program to search title of the posts. When I type title in the EditText then press Search button, my toast1 test, toast2 test, and toast3 test give correct and same value and it successfully lists what I want with Query. But the problem is that when I type different text in EditText after deleting the previous text then press enter, toast3 test(in FragmentSearch.java) stays the same and does not change value. So, it just gives the previous result, not changed result. Can anyone assist me with this? Thank you!
The problem is that you only change the value on the FragmentSearch constructor. And this constructor is only called once, and not when you press Enter.
You should change your getQuery method to have this value as a parameter.
On your MainFragment.java:
public abstract Query getQuery(DatabaseReference databaseReference, String value);
On your FragmentSearch.java:
#Override
public Query getQuery(DatabaseReference databaseReference, String value)
{
this.value = value;
Toast.makeText(getActivity().this, "value test 3: " + value, Toast.LENGTH_LONG).show();
Query postsQuery = databaseReference.child("Post").orderByChild("title").equalTo(value);
return postsQuery;
}

Categories

Resources