data is not getting displayed in retrofit - android

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.

Related

how to remove item from Recyclerview

friends...
In my project, I am creating a list of images from the server and showing in Recyclerview.
now I want to remove a particular item from the list when I click on the verify button.
I tried to hide holder.itemview but its see again when I scroll.
I just want to remove or hide that item which is verified once.
here is my code :
1) Main activity
public class MainActivity extends AppCompatActivity {
private static final String url = "www.mysite.com/api/api-id-list.php?action=imgs";
private ProgressDialog mDetailProgress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_main_activity);
LoadRecyclerView();
}
private void LoadRecyclerView() {
mDetailProgress = new ProgressDialog(this);
mDetailProgress.setTitle("Loading images");
mDetailProgress.setMessage("Please Wait...");
mDetailProgress.setCanceledOnTouchOutside(false);
mDetailProgress.show();
final RecyclerView imgList = (RecyclerView) findViewById(R.id.imgList);
imgList.setLayoutManager(new LinearLayoutManager(this));
StringRequest request = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
Image[] images = gson.fromJson(response, Image[].class);
imgList.setAdapter(new ImageAdapter(MainActivity.this, images));
mDetailProgress.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getBaseContext(), "Something went wrong..!", Toast.LENGTH_LONG);
}
});
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(request);
}}
2) ImageAdapter
public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ImageViewHolder> {
private ProgressDialog mDetailProgress;
private Context context;
private Image[] data;
Button btn_ban, btn_verify;
private View view;
public ImageAdapter (Context context, Image[] data) {
this.context = context;
this.data = data;
}
#NonNull
#Override
public ImageViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
view = inflater.inflate(R.layout.single_item, parent, false);
return new ImageViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ImageViewHolder holder, final int position) {
final Image imagelist = data[position];
holder.userCode.setText(imagelist.getCode());
Glide.with(holder.userImage.getContext()).load(imagelist.getIdPhoto()).into(holder.userImage);
btn_verify.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.itemView.setVisibility(View.GONE);
}
});
}
#Override
public int getItemCount() { return data.length; }
public class ImageViewHolder extends RecyclerView.ViewHolder {
TextView userCode;
ImageView userImage;
public ImageViewHolder(#NonNull View itemView) {
super(itemView);
userImage = (ImageView) itemView.findViewById(R.id.card_iv_img);
userCode = (TextView) itemView.findViewById(R.id.card_tv_code);
btn_ban = (Button) itemView.findViewById(R.id.btn_ban);
btn_verify = (Button) itemView.findViewById(R.id.btn_verify);
}
}}
3) Image.java
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Image {
#SerializedName("per_ID")
#Expose
private String perID;
#SerializedName("code")
#Expose
private String code;
#SerializedName("first_nm")
#Expose
private String firstNm;
#SerializedName("last_nm")
#Expose
private String lastNm;
#SerializedName("photo_ID")
#Expose
private String photoID;
#SerializedName("id_photo")
#Expose
private String idPhoto;
public String getPerID() {
return perID;
}
public void setPerID(String perID) {
this.perID = perID;
}
public Image withPerID(String perID) {
this.perID = perID;
return this;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Image withCode(String code) {
this.code = code;
return this;
}
public String getFirstNm() {
return firstNm;
}
public void setFirstNm(String firstNm) {
this.firstNm = firstNm;
}
public Image withFirstNm(String firstNm) {
this.firstNm = firstNm;
return this;
}
public String getLastNm() {
return lastNm;
}
public void setLastNm(String lastNm) {
this.lastNm = lastNm;
}
public Image withLastNm(String lastNm) {
this.lastNm = lastNm;
return this;
}
public String getPhotoID() {
return photoID;
}
public void setPhotoID(String photoID) {
this.photoID = photoID;
}
public Image withPhotoID(String photoID) {
this.photoID = photoID;
return this;
}
public String getIdPhoto() {
return idPhoto;
}
public void setIdPhoto(String idPhoto) {
this.idPhoto = idPhoto;
}
public Image withIdPhoto(String idPhoto) {
this.idPhoto = idPhoto;
return this;
}}
First make data not array, but List, so it's easy to remove item;
Secondly set listener for verify button inside ViewHolder and inside OnClick remove item and notify adapter.
btn_verify.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
data.remove(position);
notifyItemRemoved(position);
}
});
Note: Setting OnClickListener inside ViewHolder makes sure that only correct item is removed by using getAdapterPosition() to get correct position.
Position provided by onBindViewHolder might be invalid after new items are inserted.

Retrofit2 Api Call Error not showing the Result in Recycler view

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 .

iam using Retrofit library to fetch data from Database to recyclerview

am trying to Fetch the movies data from Mysql DB and show it to Recycler view
but when i run the app nothing shows
here is code i am using Retrofite Library
but i can't parse the Data to the Recycler view
i've made Adapter and Model Class normally like the Json
MainActivity.class
public class MainActivity extends AppCompatActivity {
private static final String url="http://192.168.1.109/stu/";
RecyclerView recyclerViewMovies;
List<MovieListsModels> movies;
MoviesAdapter adapter;
TextView Errortxt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Errortxt = (TextView)findViewById(R.id.txterror);
recyclerViewMovies = (RecyclerView)findViewById(R.id.recyclerview);
recyclerViewMovies.setHasFixedSize(true);
recyclerViewMovies.setLayoutManager(new LinearLayoutManager(this));
movies = new ArrayList<>();
loadDatafromServer();
}
private void loadDatafromServer() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
Api api = retrofit.create(Api.class);
Call<MovieListsModels> call = api.ShowMoviesData();
call.enqueue(new Callback<MovieListsModels>() {
#Override
public void onResponse(Call<MovieListsModels> call, Response<MovieListsModels> response) {
try {
MovieListsModels movie = response.body();
adapter = new MoviesAdapter(MainActivity.this, (List<MovieListsModels>) movie);
recyclerViewMovies.setAdapter(adapter);
}
catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<MovieListsModels> call, Throwable t) {
Errortxt.setText(t.getMessage().toString());
}
});
}
this is the interface of the methods
Api.class Interface
public interface Api {
#GET("config.php")
Call<MovieListsModels> ShowMoviesData();
}
MovieLists.class
public class MovieListsModels {
public MovieListsModels() {
}
int id;
String movie_name;
String movie_image;
String movie_genre;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getMovie_name() {
return movie_name;
}
public void setMovie_name(String movie_name) {
this.movie_name = movie_name;
}
public String getMovie_image() {
return movie_image;
}
public void setMovie_image(String movie_image) {
this.movie_image = movie_image;
}
public String getMovie_genre() {
return movie_genre;
}
public void setMovie_genre(String movie_genre) {
this.movie_genre = movie_genre;
}
public MovieListsModels(int id, String movie_name, String movie_image, String movie_genre) {
this.id = id;
this.movie_name = movie_name;
this.movie_image = movie_image;
this.movie_genre = movie_genre;
}
}
MovieAdapter.class
public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.MovieHolderView> {
private Context mContext;
private List<MovieListsModels> MovieList = new ArrayList<>();
public MoviesAdapter(Context mContext, List<MovieListsModels> movieList) {
this.mContext = mContext;
MovieList = movieList;
}
#NonNull
#Override
public MovieHolderView onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_item,parent,false);
MovieHolderView holder = new MovieHolderView(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull MovieHolderView holder, int position) {
MovieListsModels list = MovieList.get(position);
holder.txtName.setText(list.getMovie_name());
holder.txtGenre.setText(list.getMovie_genre());
Picasso.get()
.load(list.getMovie_image())
.into(holder.imgMovie);
}
#Override
public int getItemCount() {
return MovieList.size();
}
public class MovieHolderView extends RecyclerView.ViewHolder {
TextView txtName,txtGenre;
ImageView imgMovie;
public MovieHolderView(View itemView) {
super(itemView);
txtName =(TextView)itemView.findViewById(R.id.movieName);
txtGenre =(TextView)itemView.findViewById(R.id.movieGenre);
imgMovie =(ImageView)itemView.findViewById(R.id.movieImg);
}
}
}
If you receive a list of movies is better because you expect a list, I suppose
public void onResponse(Call<MovieListsModels> call, Response<MovieListsModels> response) {
try {
List<MovieListsModels> movie = response.body();
adapter = new MoviesAdapter(MainActivity.this, movies);
And I believe that not executing the notifyDataSetChanged, you can added like that:
private Context mContext;
private List<MovieListsModels> MovieList = new ArrayList<>();
public MoviesAdapter(Context mContext, List<MovieListsModels> movieList) {
this.mContext = mContext;
MovieList = movieList;
notifiyDataSetChanged();
If you are having json response of the form {..}, you are having an object response and you should expect an object as you have done i.e, Call<YourObject>
If you are having json response of the form [..], you are having an array response and you should expect an array i.e, Call<List<YourObject>>
In your case, i hope its an array(second case), So make changes as per the above answer done by #Guillodacosta
First don't forget to add the internet permission in your manifest file
<uses-permission android:name="android.permission.INTERNET" />
Second try this
Picasso.with(mContext).load(list.getMovie_image()).into(holder.imgMovie);

JSON was parse successfully but return a null data

Good day, I was watching an android tutorial.I followed it until it displayed the data successfully in the tutorial. but when I run my application it successfully parses the JSON response but it returns a null value when I try to display it.
This is my code
EstablishmentData.java
public class EstablishmentData implements Serializable {
public String estabName;
public String estabType;
public String estabAddress;
public String estabImage;
}
EstablishmentAdapter.java
public class EstablishmentAdapter extends RecyclerView.Adapter<EstablishmentAdapter.EstablishementViewHolder>{
private Context context;
private ArrayList<EstablishmentData> establishmentList;
public EstablishmentAdapter(Context context, ArrayList<EstablishmentData> establishmentList){
this.context= context;
this.establishmentList= establishmentList;
}
#Override
public EstablishementViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater= LayoutInflater.from(parent.getContext());
View view= inflater.from(parent.getContext()).inflate(R.layout.card_item, parent, false);
EstablishementViewHolder estabHolder = new EstablishementViewHolder(view);
return estabHolder;
}
#Override
public void onBindViewHolder(EstablishementViewHolder holder, int position) {
EstablishmentData establishmentData= establishmentList.get(position);
String image_url= "http://10.0.3.2/blowOut/" + establishmentData.estabImage;
Picasso.with(context)
// .load(establishmentData.estabImage)
.load(image_url)
.placeholder(R.drawable.blowout)
.error(android.R.drawable.stat_notify_error)
.into(holder.estabImage);
holder.estabName.setText(establishmentData.estabName);
holder.estabName.setTextColor(Color.rgb(255,0,0));
holder.estabAddress.setText(establishmentData.estabAddress);
holder.estabAddress.setTextColor(Color.rgb(255,0,0));
Log.d("Estab Adapter","Establishment logo: " +image_url);
Log.d("Estab Adapter","Establishment name: " +establishmentData.estabName);
Log.d("Estab Adapter","Establishment address: " +establishmentData.estabAddress);
}
#Override
public int getItemCount() {
if(establishmentList != null){
return establishmentList.size();
}
return 0;
}
//This is the ViewHolder class
public static class EstablishementViewHolder extends RecyclerView.ViewHolder{
public CardView cvItem;
public ImageView estabImage;
public TextView estabName;
public TextView estabAddress;
public EstablishementViewHolder(View itemView) {
super(itemView);
cvItem = itemView.findViewById(R.id.cvItem);
estabImage = itemView.findViewById(R.id.estabImage);
estabName = itemView.findViewById(R.id.estabName);
estabAddress = itemView.findViewById(R.id.estabAddress);
}
}
}
EstablishmentFragment.java
public class EstablishmentFragment extends Fragment {
final String TAG= "EstablishmentFragment";
RecyclerView rvItem;
CardView cvItem;
public EstablishmentFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_establishment, container, false);
rvItem= rootView.findViewById(R.id.rv_recycler_view_fragment_accounts); //fragment_establishment.xml-> rvItem
rvItem.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
rvItem.setLayoutManager(llm);
StringRequest stringRequest= new StringRequest(Request.Method.GET, AppConfig.URL_ESTABLISHMENT,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response);
ArrayList<EstablishmentData> establishmentData = new JsonConverter<EstablishmentData>()
.toArrayList(response, EstablishmentData.class);
EstablishmentAdapter adapter= new EstablishmentAdapter(getContext(), establishmentData);
rvItem.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(error != null){
Log.d(TAG, error.getMessage());
Toast.makeText(getActivity(), "Something went wrong", Toast.LENGTH_SHORT);
}
}
}
);
MySingleton.getInstance(getContext()).addToRequestQueue(stringRequest);
return rootView;
}
}
JsonConverter.class
public class JsonConverter<T> {
public JsonConverter() {
}
public ArrayList<T> toArrayList(String jsonString, Class<T> clazz) {
GsonBuilder builder = new GsonBuilder();
builder.setDateFormat("dd/MM/yy HH:mm:ss");
Gson gson = builder.create();
Type type = new JsonConverter.ListParameterizedType(clazz);
ArrayList<T> list = (ArrayList)gson.fromJson(jsonString, type);
return list;
}
public List<T> toList(String jsonString, Class<T> clazz) {
List<T> list = this.toArrayList(jsonString, clazz);
return list;
}
private static class ListParameterizedType implements ParameterizedType {
private Type type;
private ListParameterizedType(Type type) {
this.type = type;
}
public Type[] getActualTypeArguments() {
return new Type[]{this.type};
}
public Type getRawType() {
return ArrayList.class;
}
public Type getOwnerType() {
return null;
}
}
}
JSON
[{
"name": "Lechon-nan",
"type": "Lechon",
"address": "Lechon street",
"image": "jollibee.png"
}, {
"name": "Lechon",
"type": "Lechon",
"address": "Lechon",
"image": "mcdo.png"
}]
Logcat
Adapter: Establishment image: http://10.0.3.2/blowOut/null
Adapter: Establishment address: null
Adapter: Establishment name: null
Use same name for variable in your pojo class like same as in Json key
public class EstablishmentData implements Serializable {
public String name;
public String type;
public String address;
public String image;
}
Like this.

android -how to bind the image loaded from picasso to recycler view

I have list of data in MenuItemsModel(model) class along with image url and two strings fetching from the API. How can I load the image url with Picasso and how to bind the loaded image to recyclerview?
Here is my code
Code for model class
public class MenuItemsModel {
public int image;
public String itemName;
public String itemCost;
public MenuItemsModel(int image, String itemName, String itemCost) {
this.image = image;
this.itemName = itemName;
this.itemCost = itemCost;
}
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getItemCost() {
return itemCost;
}
public void setItemCost(String itemCost) {
this.itemCost = itemCost;
}
}
Here is my RecyclerAdapter class
public class MenusRecyclearView extends
RecyclerView.Adapter<MenusRecyclearView.RecyclerViewHolder> {
Context context;
List<MenuItemsModel> menuItemsModel;
public MenusRecyclearView(Context context, List<MenuItemsModel> menuItemsModel) {
this.context = context;
this.menuItemsModel = menuItemsModel;
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.menu_items_list, parent, false);
return new RecyclerViewHolder(view, context, menuItemsModel);
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
holder.imageView.setImageResource(menuItemsModel.get(position).getImage());
holder.ItemName.setText(menuItemsModel.get(position).getItemName());
holder.ItemCost.setText(menuItemsModel.get(position).getItemCost());
//Picasso.with(context).load(menuItemsModel.get(position).getImage()).into(holder.imageView);
}
#Override
public int getItemCount() {
return menuItemsModel.size();
}
public class RecyclerViewHolder extends RecyclerView.ViewHolder implements
View.OnClickListener {
public ImageView imageView;
public TextView ItemName, ItemCost;
Context ctx;
List<MenuItemsModel> menuItemsModels;
public RecyclerViewHolder(View view, Context ctx, List<MenuItemsModel> menuItemsModels) {
super(view);
this.ctx = ctx;
this.menuItemsModels = menuItemsModels;
view.setOnClickListener(this);
imageView = view.findViewById(R.id.biriyani_menu_item);
ItemName = view.findViewById(R.id.item_name);
ItemCost = view.findViewById(R.id.item_cost);
}
#Override
public void onClick(View v) {
int position = getAdapterPosition();
MenuItemsModel model = this.menuItemsModels.get(position);
Intent i = new Intent(this.ctx, CategoryDescription.class);
i.putExtra("ImageId", model.getImage());
i.putExtra("ItemName", model.getItemName());
i.putExtra("ItemCost", model.getItemCost());
this.ctx.startActivity(i);
}
}
}
** Here is my MainActivity class **
public class BiryanisActivity extends AppCompatActivity implements
View.OnClickListener, NetworkOperationListener{
RecyclerView recyclerView;
MenusRecyclearView menusRecyclearView;
RecyclerView.LayoutManager layoutManager;
List<MenuItemsModel> menuItemsModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.biriyanis_activity);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
menuItemsModel = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclearview_menu);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
recyclerView.setItemAnimator(new DefaultItemAnimator());
menusRecyclearView = new MenusRecyclearView(this, menuItemsModel);
recyclerView.setAdapter(menusRecyclearView);
HttpAdapter.getMenuItemsList(this,"MenuItemsList");
//prepareData();
}
/* public void prepareData() {
MenuItemsModel data = new MenuItemsModel(R.drawable.item5, "Chicken Dhum
Biriyani", "Rs.240");
menuItemsModel.add(data);
MenuItemsModel data1 = new MenuItemsModel(R.drawable.item2, "Chicken
Chilli Biriyani", "Rs.260");
menuItemsModel.add(data1);
MenuItemsModel data2 = new MenuItemsModel(R.drawable.item3, "Chicken
Tandhuri Biriyani", "Rs.280");
menuItemsModel.add(data2);
MenuItemsModel data3 = new MenuItemsModel(R.drawable.item4, "Chicken
Moghulai Biriyani", "Rs.230");
menuItemsModel.add(data3);
MenuItemsModel data4 = new MenuItemsModel(R.drawable.item1, "Chicken
Special Biriyani", "Rs.220");
menuItemsModel.add(data4);
MenuItemsModel data5 = new MenuItemsModel(R.drawable.item1, "Chicken
Mandi Biriyani", "Rs.210");
menuItemsModel.add(data5);
}*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return false;
}
#Override
public void onClick(View view) {
}
#Override
public void operationCompleted(NetworkResponse response) {
if (response.getStatusCode() == 200) {
if (response.getTag().equals("MenuItemsList")) {
try {
JSONObject jsonObjects = new JSONObject(response.getResponseString());
if (jsonObjects.getString("Data").equals("null")) {
Toast.makeText(this, "No Data Found", Toast.LENGTH_SHORT).show();
return;
}
JSONArray jsonArray = jsonObjects.getJSONArray("Data");
for (int j=0; j<jsonArray.length(); j++) {
JSONObject jsonObject = jsonArray.getJSONObject(j);
MenuItemsModel data = new Gson().fromJson(jsonObject.toString(),MenuItemsModel.class);
//Picasso.with(this).load(data.getImage()).into();
Picasso.with(this).load(data.getImage()).into(holder.imageView);
/* int image = data.getImage();
String name = data.getItemName();
String cost = data.getItemCost();
//picaso(image, imageView);*/
menuItemsModel.add(data);
}
MenusRecyclearView menusRecyclearView = new MenusRecyclearView(this,menuItemsModel);
recyclerView.setAdapter(menusRecyclearView);
} catch (JSONException e) {
e.printStackTrace();
}
}
} else {
Toast.makeText(this, "Failed to Connect Server, Please try again later", Toast.LENGTH_SHORT).show();
}
}
public void picaso(String path, ImageView imageView) {
if (!path.equals("")) {
Picasso.with(this).load(path).into(imageView);
}
}
}
Well, you are on the right track. You need to uncomment this line:
//Picasso.with(context).load(menuItemsModel.get(position).getImage()).into(holder.imageView);
And, the .getImage() needs to become your URL. That means, you should store the image url inside MenuItemsModel. Now your image is an int, and should be of a type of String so you can pass the URL to it.
Also see this answer here:
https://stackoverflow.com/a/41157030/5457878

Categories

Resources