Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I want to show this json in recyclerview. how can I do it?
I just want to list "user" and "exchangeName".
My Json;
{
"events": {
"101": {
"id": "0001",
"type": "exchange",
"user": "BTUser01",
"exchangeName": "BTCTurk",
"transactions": {
"send": "249",
"get": "24.1"
},
"certificate": [
"BTUser01Certificate"
]
},
"102": {
"id": "0002",
"type": "exchange",
"user": "BTUser02",
"exchangeName": "Koinim",
"transactions": {
"send": "300",
"get": "641"
},
"certificate": [
"BTUser02Certificate"
]
},
"103": {
"id": "0003",
"type": "exchange2",
"user": "BTUser03",
"exchangeName": "Koineks",
"transactions": {
"send": "823",
"get": "751"
},
"certificate": [
"BTUser03Certificate"
]
},
"104": {
"id": "0004",
"type": "exchange3",
"user": "BTUser04",
"exchangeName": "Paribu",
"transactions": {
"send": "543",
"get": "3.1"
},
"certificate": [
"BTUser04Certificate"
]
}
}
}
MainActivity;
public class MainActivity extends AppCompatActivity {
TextView ev, ev2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ev = (TextView) findViewById(R.id.ev);
ev2 = (TextView) findViewById(R.id.ev2);
Retrofit retrofit = new Retrofit.Builder().baseUrl("MYAPÄ°_ADRESS_LINK").addConverterFactory(GsonConverterFactory.create()).build();
Service service = retrofit.create(Service.class);
Call<ResponseBody> call = service.getData();
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(#NonNull Call<ResponseBody> call, #NonNull Response<ResponseBody> response) {
if (response.isSuccessful()) {
String res = null;
if (response.body() != null) {
try {
res = response.body().string();
parse(res);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
#Override
public void onFailure(#NonNull Call<ResponseBody> call, #NonNull Throwable t) {
int a = 0;
}
});
}
Model parse(String str) {
Model model = new Model();
try {
String source = str.replace("\n", "").replace("\t", "").replace("\r", "");
String s = new Gson().toJson(source);
s = s.replace("\\","");
s = s.substring(1,s.length()-1);
JSONObject object = new JSONObject(s).getJSONObject("events");
Iterator<String> iter = object.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
JSONObject value = new JSONObject(String.valueOf(object.get(key)));
model.setExternalId(Integer.parseInt(key));
model.setUser(value.getString("user"));
model.setSend(value.getString("send"));
ev.setText(model.user);
ev2.setText(model.send);
return model;
} catch (JSONException e) {
// Something went wrong!
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return model;
}
}
My Model;
public class Model {
int externalId;
int id;
String type;
String user;
String exchangeName;
Transactions transactions;
List<certificate> certificateList;
public int getExternalId() {
return externalId;
}
public void setExternalId(int externalId) {
this.externalId = externalId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getExchangeName() {
return exchangeName;
}
public void setExchangeName(String exchangeName) {
this.exchangeName = exchangeName;
}
public Transactions getTransactions() {
return transactions;
}
public void setTransactions(Transactions transactions) {
this.transactions = transactions;
}
public List<certificate> getCertificateList() {
return certificateList;
}
public void setCertificateList(List<certificate> certificateList) {
this.certificateList = certificateList;
}
class Transactions{
String send;
String get;
public String getSend() {
return send;
}
public void setSend(String send) {
this.send = send;
}
public String getGet() {
return get;
}
public void setGet(String get) {
this.get = get;
}
}
class certificate{
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
First of all you could have found this answer easily in the hundreds of tutorials and guides available.
To achieve this you will need to create a custom adapter and a custom view for the adapter item.
To preface this answer. I wasn't sure if you want to show multiple Model items in the RecyclerView, or some other data. This example assumes that you use a List<Model>, however, it's an easy change to make it work with another list of objects.
Example of how the adapter could look like
public class MyAdapter extends RecyclerView.Adapter
{
private Context _context;
private List<Model> _items;
public void setItems(List<Model> items)
{
this._items = items;
notifyDataSetChanged();
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
_context = parent.getContext();
return new MyAdapter.ItemViewHolder(parent);
}
#Override
public void onBindViewHolder(#NonNull final RecyclerView.ViewHolder holder, int position)
{
final MyAdapter.ItemViewHolder viewHolder = (MyAdapter.ItemViewHolder) holder;
final Model item = _items.get(position);
viewHolder._user.setText(item.user);
viewHolder._exchangeName.setText(item.exchangeName);
}
#Override
public int getItemCount()
{
return _items != null ? _items.size() : 0;
}
private static class ItemViewHolder extends RecyclerView.ViewHolder
{
private TextView _user;
private TextView _exchangeName;
private ItemViewHolder(ViewGroup parent)
{
super(LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_view, parent, false));
this._user = itemView.findViewById(R.id.user);
this._exchangeName = itemView.findViewById(R.id.exchange_name);
}
}
}
R.layout.adapter_view
This needs to be a view containing at least the two TextView views references from the MyAdapter above. Simple example:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#drawable/content_container"
android:orientation="vertical"
android:animateLayoutChanges="true"
android:padding="#dimen/padding_view_large"
android:layout_marginBottom="#dimen/padding_view_small">
<TextView
android:id="#+id/user"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/placeholder"
android:textColor="#color/black"
android:textSize="#dimen/text_size_medium"
android:layout_marginTop="#dimen/padding_view_small"/>
<TextView
android:id="#+id/exchange_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/placeholder"
android:textColor="#color/black"
android:textSize="#dimen/text_size_medium"
android:layout_marginTop="#dimen/padding_view_small"/>
</LinearLayout>
Binding the adapter
//First we set up the adapter and add our List<Model> object.
MyAdapter adapter = new MyAdapter();
adapter.setItems(... List<Model> items);
//Set up our RecyclerView and set the adapter.
final RecyclerView recyclerView = rootView.findViewById(R.id.model_list);
recyclerView.setLayoutManager(new LinearLayoutManager(_context));
recyclerView.setAdapter(adapter);
recyclerView.setHasFixedSize(true);
You need to first understand (and later create) the following things
RecyclerView Adapter
RecyclerView ViewHolder
After you read up on those two things the solution will be pretty clear. Just to point you in the right direction, you will have to create a custom adapter which you will use to populate your custom viewholders. Hope this helps get you going. Feel free to ask if you need any more help in this.
Related
I'm stuck somewhere in between getting json array inside a object setting it to recylerview, I have to send a key to fetch data and getting response in json array inside a object. Didn't understand solutions got here, so I'm here if Somebody can help mre understand.
////Main class
public class today_doctors extends AppCompatActivity {
viewModel_doc listViewModel;
List<model_doc> datalist;
todayDoctorAdapter adapter;
TextView clinic_name;
RecyclerView recview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_today_doctors);
recview=findViewById(R.id.rv);
recview.setLayoutManager(new LinearLayoutManager(this));
recview.addItemDecoration(new DividerItemDecoration(this, 0));
adapter=new todayDoctorAdapter(datalist);
recview.setAdapter(adapter);
clinic_name=findViewById(R.id.tvDrName);
process();
}
public void process(){
listViewModel= new ViewModelProvider(this).get(viewModel_doc.class);
listViewModel.getDatalistObserver ().observe(this, new Observer<List<model_doc>>() {
#Override
public void onChanged(List<model_doc> Models) {
if(Models!=null) {
datalist= Models;
adapter.updateList(Models);
}
else
{
recview.setVisibility(View.GONE);
Toast.makeText(today_doctors.this, "No data recieved", Toast.LENGTH_SHORT).show();
}
}
});
listViewModel.makeApiCall();
}
//////////Viewmodel class
public class viewModel_doc extends ViewModel
{
private MutableLiveData<List<model_doc>> datalist2;
public viewModel_doc(){
datalist2=new MutableLiveData<>();
}
public MutableLiveData<List<model_doc>> getDatalistObserver()
{
return datalist2;
}
public void makeApiCall()
{
apiSet apiServices= apiController.getInstance().getApi();
Call<List<model_doc>> calldoc=apiServices.getList2("ll0004");
calldoc.enqueue(new Callback<List<model_doc>>() {
#Override
public void onResponse(Call<List<model_doc>> call, Response<List<model_doc>> response) {
datalist2.postValue(response.body());
}
#Override
public void onFailure(Call<List<model_doc>> call, Throwable t) {
datalist2.postValue(null);
Log.e("Error :",t.getMessage());
}
});
}
}
///////////////////main model
public class model_doc {
String status,msg;
ArrayList<Data> data;
public model_doc(String status, String msg, ArrayList<Data> data) {
this.status = status;
this.msg = msg;
this.data = data;
}
public String getStatus() {
return status;
}
public String getMsg() {
return msg;
}
public ArrayList<Data> getData() {
return data;
}
public static class Data {
String doctor_id;
String doctor_name;
String proposed_date;
String date;
// Getters setters
public Data(String doctor_id, String doctor_name, String proposed_date, String date) {
this.doctor_id = doctor_id;
this.doctor_name = doctor_name;
this.proposed_date = proposed_date;
this.date = date;
}
public String getDoctor_id() {
return doctor_id;
}
public String getDoctor_name() {
return doctor_name;
}
public String getProposed_date() {
return proposed_date;
}
public String getDate() {
return date;
}
}
}
////api interface
#FormUrlEncoded
#POST("doctor_list")
Call<List<model_doc>>getList2(
#Field("clinic_id") String clinic_id
);
//////////////////controller
public class apiController {
private static final String url="https://xyz.in/api/";
private static apiController clientObject;
private static Retrofit retrofit;
apiController()
{
retrofit=new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
public static synchronized apiController getInstance(){
if(clientObject==null)
clientObject=new apiController();
return clientObject;
}
public apiSet getApi(){
return retrofit.create(apiSet.class);
}
}
////////////recycler adapter, made some changes in main model for nested data could handle it to adapter
public class todayDoctorAdapter extends RecyclerView.Adapter<todayDoctorAdapter.viewholder>
{
List<model_doc> datalist2;
public todayDoctorAdapter(List<model_doc> list){
this.datalist2=list;}
public void updateList(List<model_doc>list){
this.datalist2=list;
notifyDataSetChanged();
}
#NonNull
#Override
public todayDoctorAdapter.viewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType){
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_doctors,parent,false);
return new todayDoctorAdapter.viewholder(view);
}
#Override
public void onBindViewHolder(#NonNull todayDoctorAdapter.viewholder holder, int position){
holder.doctor_name.setText(String.format("Dr.%s", datalist2.get(position).getDoctor_app()));
holder.proposed_date.setText(String.format("Apt: %s","TODAY"));
String doc=datalist2.get(position).getDoctor_app();
holder.cv.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View arg0) {
Intent intent = new Intent(arg0.getContext(), PatientsUnderDoctor.class);
intent.putExtra("doc_name", doc);
arg0.getContext().startActivity(intent);
}
});
}
#Override
public int getItemCount(){
if (this.datalist2!=null){
return this.datalist2.size();
}
return 0;
}
public static class viewholder extends RecyclerView.ViewHolder{
TextView doctor_name,proposed_date;
CardView cv;
public viewholder(#NonNull View itemView) {
super(itemView);
doctor_name=itemView.findViewById(R.id.drName);
proposed_date=itemView.findViewById(R.id.apptDate);
cv=itemView.findViewById(R.id.cv_patient);
}
}
}
//////////////////json data look like this
{
"status": "success",
"msg": "Found",
"data": [
{
"doc_code": "jhjh0001",
"app_date": "2022-09-13",
"doc_name": "kjk",
"count": 1
}
]
}
I have am trying to fetch Different types of List data using Retrofit.
I have make a List and put data on that.
Can anyone suggest me how I can fetch Different Type of Model Data? I have When I tried to put Object List to my Custom model list I got this error :
java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to .....
Model Class
public class WorkType {
#SerializedName("type")
#Expose
private String type;
#SerializedName("worklist")
#Expose
private List<Object> worklist = null;
/**
* No args constructor for use in serialization
*
*/
public WorkType() {
}
/**
*
* #param worklist
* #param type
*/
public WorkType(String type, List<Object> worklist) {
super();
this.type = type;
this.worklist = worklist;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public List<Object> getWorkList() {
return worklist;
}
public void setWorkList(List<Object> worklist) {
this.worklist = worklist;
}
}
Retrofit Interface
#FormUrlEncoded
#POST("worklist")
Call<ArrayList<WorkType>> worklist(
#Field("teamid") String teamID
);
Fragment from where I make a API request
public class WorkTypeListFragment extends Fragment {
private FragmentWorkTypeListBinding binding;
private LoadingDialog loadingDialog;
private Context context;
public WorkTypeListFragment() {
// Required empty public constructor
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
this.context = context;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
binding = DataBindingUtil.inflate(inflater,R.layout.fragment_work_type_list,container,false);
init();
String teamID = getActivity().getIntent().getStringExtra("teamid");
fetchClientDetails("team1");
return binding.getRoot();
}
private void init() {
loadingDialog = new LoadingDialog(getActivity());
}
private void fetchClientDetails(String teamID){
loadingDialog.startLoadingDialog(); // Added Loading Screen
Call<ArrayList<WorkType>> call = RetrofitClient
.getInstance()
.getRetrofitApi()
.worklist(teamID);
call.enqueue(new Callback<ArrayList<WorkType>>() {
#Override
public void onResponse(Call<ArrayList<WorkType>> call, Response<ArrayList<WorkType>> response) {
try{
if(response.code() == 200){
ArrayList<WorkType> workTypeArrayList = response.body();
//Log.d("TAG", "onResponse: "+workTypeArrayList.get(1).getWorkList().get(0).getClientname());
assert workTypeArrayList != null;
bindDataToView(workTypeArrayList);
} else {
Toast.makeText(getContext(), "Response Code is no 200", Toast.LENGTH_SHORT).show();
loadingDialog.dismissDialog();
}
}catch(Exception e){
e.printStackTrace();
}
}
#Override
public void onFailure(Call<ArrayList<WorkType>> call, Throwable t) {
Toast.makeText(getContext(), "Something Went wrong! Please try again later!", Toast.LENGTH_SHORT).show();
loadingDialog.dismissDialog();
}
});
}
private void bindDataToView(ArrayList<WorkType> workTypeArrayList) {
WorkTypesAdapter adapter = new WorkTypesAdapter(context,workTypeArrayList);
binding.workTypeRv.setLayoutManager(new LinearLayoutManager(context));
binding.workTypeRv.setAdapter(adapter);
}
}
RecyclearView Adapter Class
public class WorkTypesAdapter extends RecyclerView.Adapter<WorkTypesAdapter.ViewHolder> {
private Context mCtx;
private List<WorkType> workTypeList;
private final static int survey = 1;
private final static int service = 2;
private final static int maintain = 3;
public WorkTypesAdapter(Context mCtx, List<WorkType> modelServiceList) {
this.mCtx = mCtx;
this.workTypeList = modelServiceList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.layout_worktype, null);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
WorkType currentWorkType = workTypeList.get(position);
String modelClass = currentWorkType.getType();
List<Object> objectList = currentWorkType.getWorkList();
switch (modelClass){
/*case "survey":
List<SurveyWorkList> surveyWorkLists = new ArrayList<>();
for (Object object : objectList) {
surveyWorkLists.add((SurveyWorkList) object);
holder.workType.setText(currentWorkType.getType());
holder.workTypeCount.setText(surveyWorkLists.size());
}
break;*/
case "service":
List<ServiceWorkList> serviceWorkLists = new ArrayList<>();
for (Object object : objectList) {
serviceWorkLists.add((ServiceWorkList) object);
}
/*holder.workType.setText(currentWorkType.getType());
holder.workTypeCount.setText(serviceWorkLists.size());*/
break;
/*case "maintain":
List<MaintainWorkList> maintainWorkLists = new ArrayList<>();
for (Object object : objectList) {
maintainWorkLists.add((MaintainWorkList) object);
}
holder.workType.setText(currentWorkType.getType());
holder.workTypeCount.setText(maintainWorkLists.size());
break;*/
default:
//Do nothing
}
/*holder.workType.setText(modelService.getType());
holder.workTypeCount.setText(workTypeList.size());*/
}
#Override
public int getItemCount() {
return workTypeList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView workType, workTypeCount;
public ViewHolder(#NonNull View itemView) {
super(itemView);
workType = itemView.findViewById(R.id.work_type_tv);
workTypeCount = itemView.findViewById(R.id.work_type_count_tv);
}
}
}
API response
[
{
"type": "survey",
"worklist": []
},
{
"type": "service",
"worklist": [
{
"serviceid": "HS2020031613054318",
"clientid": "R2020031612594874",
"clientname": "********",
"companyname": "",
"membership": "",
"phone": [
"*********"
],
"**************",
"account": 2,
"slot": "morning",
"orderstatus": "Completed",
"orderstatuscode": "8",
"remarks": ""
}
]
},
{
"type": "maintain",
"worklist": []
}
]
The survey and maintain will have different Parameter.
I have found the answer.
First, you have to make a model class:
#SerializedName("contents")
#Expose
private JsonElement contents = null;
In my API I got an element type. So you know in which type you have to parse the data. Let's say you have three types. So we will create a Type object:
switch(type)
case 1:
Type type = new TypeToken<ArrayList<Banner>>() {
}.getType();
ArrayList<Banner> bannerList = new Gson().fromJson(baseModel.getContents(), type);
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.
I created a RecyclerView with data loaded locally using a standard model and adapter approach, the views that the RecyclerView recycles hold an image and 3 text views. I'd like to populate these views using data from a Firebase Database. I've created the data on Firebase which looks like this:
{
"items" : {
"item 1" : {
"colour-value" : "000000",
"manufacturer" : "Manufacturer 1",
"name" : "Name 1",
"type" : "Type 1"
},
"item 2" : {
"colour-value" : "ffff00",
"manufacturer" : "Manufacturer 2",
"name" : "Name 2",
"type" : "Type 2"
},
"item 3" : {
"colour-value" : "ff0000",
"manufacturer" : "Manufacturer 3",
"name" : "Name 3",
"type" : "Type 3"
}
}
}
I've already added the dependencies and have Firebase Auth set up and working. The data will never be changed by the user but may be changed manually in the back end from time to time. The image is a single white png with the colour changed based on the colour-value.
Everything that I've seen appears to be overly complex for what I need and I'm convinced it doesn't need to be but can't whittle down what I need to feed this data into the RecyclerView.
Any pointers? Thanks.
EDIT - All special characters have been removed from data.
ItemAdapter
public class ItemAdapter extends
RecyclerView.Adapter<ItemAdapter.MyViewHolder> {
private Context mContext;
private List<Item> itemList;
class MyViewHolder extends RecyclerView.ViewHolder {
TextView itemName, itemManufacturer, itemType;
private MyViewHolder (View view) {
super(view);
itemName = view.findViewById(R.id.item_name);
itemManufacturer = view.findViewById(R.id.item_manufacturer);
itemType = view.findViewById(R.id.item_type);
}
}
ItemAdapter(Context mContext, List<Item> itemList) {
this.mContext = mContext;
this.itemList = itemList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final Item.MyViewHolder holder, int position) {
Item item = itemList.get(position);
holder.itemName.setText(item.getItemName());
holder.itemManufacturer.setText(item.getItemManufacturer());
holder.itemType.setText(item.getItemType());
}
void filter (ArrayList<Item> newList) {
itemList = new ArrayList<>();
itemList.addAll(newList);
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return itemList.size();
}
}
The first problem here in your JSON you can not have a hyphen or spaces in your keys as firebase will do a mapping based on keys to POJO member variables and java does not allow special characters in namings.
So if you change your keys just do this
Make a POJO
public class SampleModel {
private int colorValue;
private String manufacturer;
private String name;
private String type;
public int getColorValue() {
return colorValue;
}
public void setColorValue(int colorValue) {
this.colorValue = colorValue;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
then create your database reference and get the data and update the list
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DatabaseReference myRef = FirebaseDatabase.getInstance().getReference("items");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//you have data now traverse
for (DataSnapshot child: dataSnapshot.getChildren()){
//your data may come up in map so handle here
HashMap<String,SampleModel> hashMap = (HashMap<String,SampleModel>)child.getValue();
//if everything is okay then just iterate over the map and create a list
List<SampleModel> sampleModels = new ArrayList<>()
for (HashMap.Entry<String,SampleModel> modelEntry:hashMap.entrySet()){
sampleModels.add(modelEntry.getValue());
}
mainList.addAll(sampleModels);
adapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
//for some reason data did't show up
}
});
Edit: Added
HashMap<String,SampleModel> hashMap = (HashMap<String,SampleModel>)child.getValue();
I've been working with Recycler view Android. I try to make a Recycler view from API Response. But, the list didn't show up, my adapter was not working. When i tried to debug this program, I got List<Produclist> list is null.
This my JSON Response from API
{
"code": 0,
"data": [
{
"product_list": [
{
"return_level": 0,
"image": "ee0c97c5-1752-4f1a-b713-2308eb1284d8",
"risk_level": "Aggresive",
"code": "P0011",
"price": {
"date": null,
"value": 0
},
"name": "Dana Ekuitas Prima"
},
{
"return_level": 0,
"image": "ee0c97c5-1752-4f1a-b713-2308eb1284d8",
"risk_level": "Aggresive",
"code": "P0001",
"price": {
"date": "2017-01-03T11:44:52.6152Z",
"value": 150000
},
"name": "Manulife Dana Saham"
},
{
"return_level": 0,
"image": "ee0c97c5-1752-4f1a-b713-2308eb1284d8",
"risk_level": "Aggresive",
"code": "P0008",
"price": {
"date": null,
"value": 0
},
"name": "Trim Kapital Plus"
},
{
"return_level": 0,
"image": "ee0c97c5-1752-4f1a-b713-2308eb1284d8",
"risk_level": "Aggresive",
"code": "P0004",
"price": {
"date": "2017-01-03T11:44:52.6152Z",
"value": 150000
},
"name": "Manulife Syariah Sektoral Amanah"
}
],
"type": "Reksa Dana Saham"
}
],
"info": "Product list successfully loaded"
}
This My setter getter
public class ProductListResponse {
#SerializedName("code")
#Expose
private Integer code;
#SerializedName("info")
#Expose
private String info;
#SerializedName("data")
#Expose
private List<CategoryType> listCategory = new ArrayList<>();
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public List<CategoryType> getListCategory() {
return listCategory;
}
public void setListCategory(List<CategoryType> listCategory) {
this.listCategory = listCategory;
}
}
Setter getter of category type
public class CategoryType {
#SerializedName("type")
#Expose
private String type;
#SerializedName("product_list")
#Expose
private List<ProductList> productList = new ArrayList<ProductList>();
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public List<ProductList> getProductList() {
return productList;
}
public void setProductList(List<ProductList> productList) {
this.productList = productList;
}
}
Setter getter of ProductList
public class ProductList implements Serializable {
#SerializedName("code")
#Expose
private String code;
#SerializedName("name")
#Expose
private String name;
#SerializedName("price")
#Expose
private Price price;
#SerializedName("risk_level")
#Expose
private String riskLevel;
#SerializedName("return_level")
#Expose
private Double returnLevel;
#SerializedName("image")
#Expose
private String image;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getRiskLevel() {
return riskLevel;
}
public void setRiskLevel(String riskLevel) {
this.riskLevel = riskLevel;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Price getPrice() {
return price;
}
public void setPrice(Price price) {
this.price = price;
}
public Double getreturnLevel() {
return returnLevel;
}
public void setReturnLevel(Double returnLevel) {
this.returnLevel = returnLevel;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
This my Activity
public class ProductActivity extends AppCompatActivity {
private RecyclerView rvView;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
public List<ProductList> list;
Context context;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.f_list_of_product);
request(constructSignUpRequest());
rvView = (RecyclerView) findViewById(R.id.rv);
rvView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
rvView.setLayoutManager(layoutManager);
adapter = new ProductAdapter(context, list);
rvView.setAdapter(adapter);
}
public BTNService.Api getApi() {
return getBTNService().getApi();
}
public BTNService getBTNService() {
return new BTNService(this);
}
void request(final ProductListRequest productListRequest) {
getApi().loadproductlist(productListRequest.getCode())
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(new Observer<ProductListResponse>() {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
Timber.e(e.getLocalizedMessage());
}
#Override
public void onNext(ProductListResponse response) {
if (response != null) {
Intent intent = new Intent(ProductActivity.this, ProductList.class);
startActivity(intent);
}
}
});
}
public ProductListRequest constructSignUpRequest() {
ProductListRequest request = new ProductListRequest();
request.setCode(Category);
return request;
}
}
This my Adapter
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.CatalogueHolder> {
private Context context;
private List<ProductList> list;
public ProductAdapter(Context context, List<ProductList> list) {
this.context = context;
this.list = list;
}
#Override
public CatalogueHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_product, parent, false);
CatalogueHolder catalogueHolder = new CatalogueHolder(itemView);
return catalogueHolder;
}
#Override
public void onBindViewHolder(CatalogueHolder holder, int position) {
final ProductList item = list.get(position);
holder.itemView.setTag(item);
holder.productName.setText(item.getName());
}
#Override
public int getItemCount() {
return list != null ? list.size() : 0;
}
public static class CatalogueHolder extends RecyclerView.ViewHolder {
#Bind(R.id.productname)
TextView productName;
#Bind(R.id.typeProduct)
TextView typeProduct;
#Bind(R.id.price)
TextView price;
#Bind(R.id.date)
TextView date;
public CatalogueHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}
Sorry, if it's quite long. I have to show all my code to make it clear. I really need your help guys. Thanks
Set adapter inside onComplete method:
void request(final ProductListRequest productListRequest) {
getApi().loadproductlist(productListRequest.getCode())
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(new Observer<ProductListResponse>() {
#Override
public void onCompleted() {
rvView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
rvView.setLayoutManager(layoutManager);
adapter = new ProductAdapter(context, list);
rvView.setAdapter(adapter);
}
#Override
public void onError(Throwable e) {
Timber.e(e.getLocalizedMessage());
}
#Override
public void onNext(ProductListResponse response) {
if (response != null) {
Intent intent = new Intent(ProductActivity.this, ProductList.class);
startActivity(intent);
}
}
});
}