Parse JSON data into HorizontalScrollView with Retrofit 2 - java

I need to parse JSON data into HorizontalScrollView with Retrofit2. I parsed it into ListView succesfully, but I haven't imagination how to do it into HorizontalScrollView. Google can't give me right answer.
My code with ListView below.
P.S. I want to do HorizontalScrollView instead of ListView.
Like this.
MyForecastAdapter.java
public class MyForecastAdapter extends ArrayAdapter<Forecast> {
List<Forecast> forecastList;
Context context;
private LayoutInflater inflater;
public MyForecastAdapter(Context context, List<Forecast> objects) {
super(context, 0, objects);
this.context = context;
this.inflater = LayoutInflater.from(context);
forecastList = objects;
}
#Override
public Forecast getItem(int position) {
return forecastList.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
if (convertView == null) {
View view = inflater.inflate(R.layout.activity_row, parent, false);
viewHolder = ViewHolder.create((RelativeLayout) view);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
Forecast item = getItem(position);
viewHolder.textViewTemp.setText(item.getMain().getTemp());
viewHolder.textViewHumidity.setText(item.getMain().getHumidity());
return viewHolder.relativeLayout;
}
private static class ViewHolder {
public final RelativeLayout relativeLayout;
public final TextView textViewTemp;
public final TextView textViewHumidity;
private ViewHolder(RelativeLayout relativeLayout, TextView textViewTemp, TextView textViewHumidity) {
this.relativeLayout = relativeLayout;
this.textViewTemp = textViewTemp;
this.textViewHumidity = textViewHumidity;
}
public static ViewHolder create(RelativeLayout relativeLayout) {
TextView textViewTemp = (TextView) relativeLayout.findViewById(R.id.textViewTemp);
TextView textViewHumidity = (TextView) relativeLayout.findViewById(R.id.textViewHumidity);
return new ViewHolder(relativeLayout, textViewTemp, textViewHumidity);
}
}
}
ForecastList.java
public class ForecastList {
#SerializedName("list")
#Expose
private ArrayList<Forecast> forecasts = new ArrayList<>();
public ArrayList<Forecast> getForecasts() {
return forecasts;
}
public void setForecasts(ArrayList<Forecast> forecasts) {
this.forecasts = forecasts;
}
}
Forecast.java - getters/setters.
ApiService.java
public interface ApiService {
#GET("/data/2.5/forecast?q=Kirov,ru&appid=/../")
Call<ForecastList> getMyJSON();
}
RetrofitClient.java
public class RetrofitClient {
private static final String ROOT_URL = "http://api.openweathermap.org";
private static Retrofit getRetrofitInstance() {
return new Retrofit.Builder().baseUrl(ROOT_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
public static ApiService getApiService() {
return getRetrofitInstance().create(ApiService.class);
}
}
MainActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
forecastList = new ArrayList<>();
parentView = findViewById(R.id.parentLayout);
listView = (ListView) findViewById(R.id.listView);
ApiService apiService = RetrofitClient.getApiService();
Call<ForecastList> call = apiService.getMyJSON();
call.enqueue(new Callback<ForecastList>() {
#Override
public void onResponse(Call<ForecastList> call, Response<ForecastList> response) {
if (response.isSuccessful()) {
forecastList = response.body().getForecasts();
adapter = new MyForecastAdapter(MainActivity.this, forecastList);
listView.setAdapter(adapter);
} else {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<ForecastList> call, Throwable t) {
}
});
}

You can use horizonatal Scroll View using Recycle View with LinearLayoutManager with constructor new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
Use this code .....
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
forecastList = new ArrayList<>();
parentView = findViewById(R.id.parentLayout);
LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
myList = (RecyclerView) findViewById(R.id.listView);
myList.setLayoutManager(layoutManager);
ApiService apiService = RetrofitClient.getApiService();
Call<ForecastList> call = apiService.getMyJSON();
call.enqueue(new Callback<ForecastList>() {
#Override
public void onResponse(Call<ForecastList> call, Response<ForecastList> response) {
if (response.isSuccessful()) {
forecastList = response.body().getForecasts();
adapter = new MyForecastAdapter(MainActivity.this, forecastList);
myList.setAdapter(adapter);
} else {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<ForecastList> call, Throwable t) {
}
});
}
and change ListView into RecycleView in XML and in code also.....

Related

I am facing an issue with RecyclerView no adapter attached, even after setting adapter an layout manager. I a

I want to fetch data from json file from the internet using url, After doing all the codes RecyclerView says no adapter attached. I am not able to find out what is wrong with my code.
public class MainActivity extends AppCompatActivity {
private String urlData = "https://vast-shore-74260.herokuapp.com/banks?city=MUMBAI";
private RecyclerView recyclerView;
private RecyclerView.Adapter Radapter;
private List<ListItem> listItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
//Using this listitem in recyclerView works just fine but when i try to to parse json file, RecyclerView says no adapter attached.
/*listItems = new ArrayList<>();
for (int i=0;i<=10;i++)
{
ListItem listItem = new ListItem(
"SBI"+(i+1),
"Lorem ipsum",
"SBIN00009945",
"khanapara",
"9945",
"ghy",
"kamrup",
"assam"
);
listItems.add(listItem);
}
Radapter = new MyAdapter(listItems,this);
recyclerView.setAdapter(Radapter);*/
Spinner dropdown = findViewById(R.id.spinner);
String[] items = new String[]{"Select City","Mumbai","Bangalore","Chennai"};
ArrayAdapter<String>adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,items)
{
#Override
public boolean isEnabled(int position)
{
if (position == 0)
{
return false;
}
else
{
return true;
}
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent)
{
View view = super.getDropDownView(position,convertView,parent);
TextView txtView = (TextView)view;
if (position == 0)
{
txtView.setTextColor(Color.GRAY);
}
else
{
txtView.setTextColor(Color.BLACK);
}
return view;
}
};
dropdown.setAdapter(adapter);
listItems = new ArrayList<>();
loadRecyclerViewData();
}
private void loadRecyclerViewData()
{
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading Data...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(
Request.Method.GET,
urlData,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray array = jsonObject.getJSONArray(urlData);
for (int i=0; i<array.length();i++)
{
JSONObject o = array.getJSONObject(i);
ListItem item = new ListItem(
o.getString("bank_name"),
o.getString("address"),
o.getString("ifsc"),
o.getString("branch"),
o.getInt("bank_id"),
o.getString("city"),
o.getString("district"),
o.getString("state")
);
listItems.add(item);
}
/*Radapter = new MyAdapter(listItems,getApplicationContext());
recyclerView.setAdapter(Radapter);*/
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),error.getMessage(),Toast.LENGTH_LONG).show();
Log.e("errorcode",error.getMessage());
}
}
);
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
There might be some problem in this code:
Radapter = new MyAdapter(listItems,getApplicationContext());
recyclerView.setAdapter(Radapter);
This is the Adapter class
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<ListItem> listItems;
private Context context;
public MyAdapter(List<ListItem> listItemAdap, Context context) {
this.listItems = listItemAdap;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder( ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_items,parent,false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
ListItem listItem = listItems.get(position);
holder.txtviewBankName.setText(listItem.getBank_name());
holder.txtviewAddress.setText(listItem.getAddress());
holder.txtviewIfsc.setText(listItem.getIfsc());
holder.txtviewBranch.setText(listItem.getBranch());
holder.txtviewBankId.setText(listItem.getBank_id());
holder.txtviewCity.setText(listItem.getCity());
holder.txtviewDistrict.setText(listItem.getDistrict());
holder.txtviewState.setText(listItem.getState());
}
#Override
public int getItemCount() {
return listItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder
{
public TextView txtviewBankName;
public TextView txtviewAddress;
public TextView txtviewIfsc;
public TextView txtviewBranch;
public TextView txtviewBankId;
public TextView txtviewCity;
public TextView txtviewDistrict;
public TextView txtviewState;
public ViewHolder(View itemView) {
super(itemView);
txtviewBankName = (TextView)itemView.findViewById(R.id.bankName);
txtviewAddress = (TextView)itemView.findViewById(R.id.address);
txtviewIfsc = (TextView)itemView.findViewById(R.id.ifsc);
txtviewBranch = (TextView)itemView.findViewById(R.id.branch);
txtviewBankId = (TextView)itemView.findViewById(R.id.bankId);
txtviewCity = (TextView)itemView.findViewById(R.id.city);
txtviewDistrict = (TextView)itemView.findViewById(R.id.district);
txtviewState = (TextView)itemView.findViewById(R.id.state);
}
}
}
Your JSON string has some wrong characters, it should be like this
[{"ifsc":"ABHY0065001","bank_id":60,"branch":"RTGS-HO","address":"ABHYUDAYA BANK BLDG., B.NO.71, NEHRU NAGAR, KURLA (E), MUMBAI-400024","city":"MUMBAI","district":"GREATER MUMBAI","state":"MAHARASHTRA","bank_name":"ABHYUDAYA COOPERATIVE BANK LIMITED"}]
then for parsing this json you can use the com.google.Gson library like this
Type listType = new TypeToken<ArrayList<ListItem>>() {}.getType();
String s = "[{\"ifsc\":\"ABHY0065001\",\"bank_id\":60,\"branch\":\"RTGS-HO\",\"address\":\"ABHYUDAYA BANK BLDG., B.NO.71, NEHRU NAGAR, KURLA (E), MUMBAI-400024\",\"city\":\"MUMBAI\",\"district\":\"GREATER MUMBAI\",\"state\":\"MAHARASHTRA\",\"bank_name\":\"ABHYUDAYA COOPERATIVE BANK LIMITED\"}]";
List<ListItem> items = new Gson().fromJson(s, listType);
then you can set this list as input into your Adapter then assign your adapter to your recycler.

Change value recycleview.adapter and save it to textview in mainactivity?

When I change the value from recycleview.adapter, i want to set it the value to textview in mainactivity, how to do it?
it will be like this,
the recycle data retreive from my json, so it will be random and many data,
when I change or add the value of "total win" to more than "0", the textview at bottom will be appear, and "total all" will count from data I add, when its done, I want to send the "result" value to next activity or post and save it to mysql dbase,
here my code of MainActivity :
...
private List<Details> listDetails = new ArrayList<>();
private RecyclerAdapter viewAdapter;
#BindView(R.id.recyclerView)
RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view);
ButterKnife.bind(this);
viewAdapter = new RecyclerAdapter(this, listDetails);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(viewAdapter);
getMyData();
}
...
private void getMyData() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(AppConfig.URL_MAIN)
.addConverterFactory(GsonConverterFactory.create())
.build();
...
});
...
My RecycleAdapter code :
...
private Context context;
private List<Details> listDetails;
public RecyclerAdapter(Context context, List<Details> listDetails) {
this.context = context;
this.listDetails = listDetails;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_view, parent, false);
ViewHolder holder = new ViewHolder(v);
return holder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final Details getSet = listDetails.get(position);
holder.tvName.setText(getSet.getName());
holder.numberPickerTotalWin.setValueChangedListener(new ValueChangedListener() {
#Override
public void valueChanged(int value, ActionEnum action) {
Toast.makeText(context, position + value + " Clicked", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return listDetails.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
#BindView((R.id.nP))
NumberPicker numberPickerTotalWin;
#BindView(R.id.tvName)
TextView tvName;
public ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
...
}
}
Check the code
YourActivity ... implements RecyclerViewItemClick
private List<Details> listDetails = new ArrayList<>();
private RecyclerAdapter viewAdapter;
#BindView(R.id.recyclerView)
RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view);
ButterKnife.bind(this);
viewAdapter = new RecyclerAdapter(this, listDetails, this);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(viewAdapter);
getMyData();
}
...
private void getMyData() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(AppConfig.URL_MAIN)
.addConverterFactory(GsonConverterFactory.create())
.build();
...
});
RecyclerViewAdapter
private RecyclerViewItemClick mListener;
public RecyclerAdapter(Context context, List<Details> listDetails, RecyclerViewItemClick listener) {
this.context = context;
this.listDetails = listDetails;
this.mListener = listener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_view, parent, false);
ViewHolder holder = new ViewHolder(v, mListener);
return holder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final Details getSet = listDetails.get(position);
holder.tvName.setText(getSet.getName());
holder.numberPickerTotalWin.setValueChangedListener(new ValueChangedListener() {
#Override
public void valueChanged(int value, ActionEnum action) {
Toast.makeText(context, position + value + " Clicked", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return listDetails.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
#BindView((R.id.nP))
NumberPicker numberPickerTotalWin;
#BindView(R.id.tvName)
TextView tvName;
public ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (mListener != null){
//you can access to the current position if you want -> getLayoutPosition()
mListener.yourMethod();
}
}
public interface RecyclerViewItemClick {
void yourMethod();
}
}

How to change text in Fragment (outside recyclerVIew) from within RecyclerView viewHolder onClick

My cart
This is what i need.
Total value need to be updated when one item removed.
I managed to remove the item and get the total value as json respose in adapter viewholder . don't know how to set the update the text in Fragment.
this is my cart fragment
Cart.java
public class Cart extends Fragment {
public Cart() {
// Required empty public constructor
}
Context context;
Activity activity;
List<GetDataAdapter> GetDataAdapter1;
RecyclerView recyclerView;
RecyclerView.LayoutManager recyclerViewlayoutManager;
RecyclerView.Adapter recyclerViewadapter;
String GET_JSON_DATA_HTTP_URL = "http://192.168.0.106/slbros/index.php/get/cart?p_d_id=12&lan=en";
String Total_URL = "http://192.168.0.106/slbros/index.php/get/total?p_d_id=12";
String JSON_CDID = "cart_dtl_id";
String JSON_IMG_URL = "img_url";
String JSON_QTY = "qty";
String JSON_NAME = "name";
String JSON_UNIT = "unit";
String JSON_PRICE = "price";
String JSON_P_ID = "product_id";
JsonArrayRequest jsonArrayRequest;
RequestQueue requestQueue;
ProgressBar progressBar;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_cart, container, false);
TextView total_tv = (TextView)v.findViewById(R.id.total_payment_value);
//recycler view
GetDataAdapter1 = new ArrayList<>();
recyclerView = (RecyclerView) v.findViewById(R.id.rv_cart_list);
progressBar = (ProgressBar) v.findViewById(R.id.progressBar2);
recyclerView.setHasFixedSize(true);
recyclerViewlayoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(recyclerViewlayoutManager);
progressBar.setVisibility(View.VISIBLE);
JSON_DATA_WEB_CALL();
return v;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//you can set the title for your toolbar here for different fragments different titles
getActivity().setTitle("Cart");
}
public void JSON_DATA_WEB_CALL() {
jsonArrayRequest = new JsonArrayRequest(GET_JSON_DATA_HTTP_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
progressBar.setVisibility(View.GONE);
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressBar.setVisibility(View.GONE);
Toast.makeText(getContext(), "some error....", Toast.LENGTH_SHORT).show();
}
}
);
requestQueue = Volley.newRequestQueue(getContext());
jsonArrayRequest.setRetryPolicy(new DefaultRetryPolicy(60000, 0, 1));
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
GetDataAdapter GetDataAdapter2 = new GetDataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setImg_url(json.getString(JSON_IMG_URL));
GetDataAdapter2.setName(json.getString(JSON_NAME));
GetDataAdapter2.setPrice(json.getInt(JSON_PRICE));
GetDataAdapter2.setProduct_id(json.getInt(JSON_P_ID));
GetDataAdapter2.setCart_dtl_id(json.getInt(JSON_CDID));
GetDataAdapter2.setProduct_qty(json.getInt(JSON_QTY));
} catch (JSONException e) {
e.printStackTrace();
}
GetDataAdapter1.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapterCart(GetDataAdapter1, getContext());
recyclerView.setAdapter(recyclerViewadapter);
}}
this is my adapter
RecyclerViewAdapterCart.java
public class RecyclerViewAdapterCart extends RecyclerView.Adapter<RecyclerViewAdapterCart.ViewHolder> {
JsonArrayRequest jsonArrayRequest ;
RequestQueue requestQueue ;
String baseURL = "http://192.168.0.106/slbros/index.php/";
Context context;
Activity activity;
List<GetDataAdapter> getDataAdapter;
ImageLoader imageLoader1;
public RecyclerViewAdapterCart(List<GetDataAdapter> getDataAdapter, Context context) {
super();
this.getDataAdapter = getDataAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.cart_list_item, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder Viewholder, int position) {
GetDataAdapter getDataAdapter1 = getDataAdapter.get(position);
imageLoader1 = ServerImageParseAdapter.getInstance(context).getImageLoader();
imageLoader1.get(getDataAdapter1.getImg_url(),
ImageLoader.getImageListener(
Viewholder.product_image_view,//Server Image
R.mipmap.ic_launcher,//Before loading server image the default showing image.
android.R.drawable.ic_dialog_alert //Error image if requested image dose not found on server.
)
);
Viewholder.product_image_view.setImageUrl(getDataAdapter1.getImg_url(), imageLoader1);
Viewholder.product_name_TextView.setText(getDataAdapter1.getName()+" - "+String.valueOf(getDataAdapter1.getProduct_qty()));
Viewholder.product_price_qty_TextView.setText(getDataAdapter1.getPrice()+".00 Rs X "+String.valueOf(getDataAdapter1.getProduct_qty()));
Viewholder.product_t_price_TextView.setText(String.valueOf(getDataAdapter1.getProduct_qty()*getDataAdapter1.getPrice())+".00 Rs");
Viewholder.product_id_TextView.setText(String.valueOf(getDataAdapter1.getProduct_id()));
Viewholder.cart_dtl_id_TextView.setText(String.valueOf(getDataAdapter1.getCart_dtl_id()));
}
#Override
public int getItemCount() {
return getDataAdapter.size();
}
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public NetworkImageView product_image_view;
public TextView product_name_TextView;
public TextView product_price_qty_TextView;
public TextView product_t_price_TextView;
public TextView product_id_TextView;
public TextView cart_dtl_id_TextView;
public Button p_cancel_btn;
public ViewHolder(View itemView) {
super(itemView);
product_image_view = (NetworkImageView) itemView.findViewById(R.id.item_image1);
product_name_TextView = (TextView) itemView.findViewById(R.id.product_name);
product_price_qty_TextView = (TextView) itemView.findViewById(R.id.p_qty_price);
product_t_price_TextView = (TextView) itemView.findViewById(R.id.p_t__price);
product_id_TextView = (TextView) itemView.findViewById(R.id.product_id_tv);
cart_dtl_id_TextView = (TextView) itemView.findViewById(R.id.cart_dtl_id_tv);
p_cancel_btn = (Button)itemView.findViewById(R.id.p_cancel_btn);
// set item view
p_cancel_btn.setOnClickListener(this);
}
#Override
public void onClick(final View v) {
String str = product_name_TextView.getText().toString();
//Toast.makeText(v.getContext(), str, Toast.LENGTH_SHORT).show();
String cart_dtl_id = cart_dtl_id_TextView.getText().toString();
String url = baseURL + "delete/select?cart_dtl_id="+cart_dtl_id;
jsonArrayRequest = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//progressBar.setVisibility(View.GONE);
Toast.makeText(v.getContext(), "response -- " + response, Toast.LENGTH_LONG).show();
// here, I have to change the total TextView in Fragment
// Total_TextView.setText("1000rs")
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(v.getContext(), "error", Toast.LENGTH_LONG).show();
}
}
);
requestQueue = Volley.newRequestQueue(v.getContext());
jsonArrayRequest.setRetryPolicy(new DefaultRetryPolicy(60000,0,1));
requestQueue.add(jsonArrayRequest);
getDataAdapter.remove(getAdapterPosition());
notifyItemRemoved(getAdapterPosition());
notifyItemRangeChanged(getAdapterPosition(),getDataAdapter.size());
}
}}
Thanks in Advance
add to ReyclerView.
private ItemsChangedListener itemsChangedListener;
public interface ItemsChangedListener {
void onItemsChanged(int sum);
}
public void setItemsChangedListener(ItemsChangedListener listener) {
this.itemsChangedListener = listener;
}
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//progressBar.setVisibility(View.GONE);
// Calc here the Value if you can.
if(listener != null) listener.onItemsChanged(sum);
}
Fragment
public class Cart extends Fragment implements ItemsChangedListener
recyclerView.setItemsChangedListener(this);
#override
public void onItemsChanged(int sum) {
//Update TextView
}

How to scroll to load More Data On Recycler View?

i want know how to scroll to get more data on my recycler view
example my using wordpress api to have 10post from my website
and i want to get 5 per load in recycler and scroll more to get 5 post more
but i don't know how to coding please than a look and give me some correct idea !!
News_list.java
/**
* A simple {#link Fragment} subclass.
*/
public class News_List extends Fragment {
private static final String URL = "https://chsknews.com/wp-json/wp/v2/posts/";
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private List<News_Item> news_itemList;
private SwipeRefreshLayout swipeRefreshLayout;
public News_List() {
// 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_news__list, container, false);
swipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_refresh);
recyclerView = (RecyclerView) rootView.findViewById(R.id.MRecyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
news_itemList = new ArrayList<>();
News_Loader();
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
News_Loader();
Toast.makeText(getContext(),"ដំណើរការជោគជ័យក្នុងការទាញយកពត៏មានចុងក្រោយ",Toast.LENGTH_SHORT).show();
news_itemList.clear();
}
});
return rootView;
}
private void News_Loader() {
final ProgressDialog progressDialog = new ProgressDialog(getContext());
progressDialog.setMessage("Loading News");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET,
URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
//JSONObject jsonObject = new JSONObject(response);
JSONArray array = new JSONArray(response);
for (int i = 0; i < array.length(); i++){
JSONObject o = array.getJSONObject(i);
// Log.v("ID",o.getJSONObject("content").optString("rendered"));
news_itemList.add(new News_Item(
o.getJSONObject("title").getString("rendered"),
o.getString("date"),
o.getJSONObject("better_featured_image").getString("source_url"),
o.getString("date"),
o.getJSONObject("content").getString("rendered"))
);
// news_itemList.add(news_item);
}
adapter = new CustomAdapter(news_itemList,getContext());
recyclerView.setAdapter(adapter);
if (swipeRefreshLayout.isRefreshing())
{
swipeRefreshLayout.setRefreshing(false);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(getContext(), error.getMessage(),Toast.LENGTH_LONG).show();
if (swipeRefreshLayout.isRefreshing())
{
swipeRefreshLayout.setRefreshing(false);
}
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
requestQueue.add(stringRequest);
}
}
Adapter Class
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {
private List<News_Item> news_items;
private Context context;
public CustomAdapter(List<News_Item> news_items, Context context) {
this.news_items = news_items;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_view,parent,false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
final News_Item news_item = news_items.get(position);
holder.title.setText(Html.fromHtml(news_item.getTitle()));
holder.news_date.setText((news_item.getNews_date()));
Picasso.with(context)
.load(news_item.getImage_url())
.fit()
.into(holder.news_img);
holder.news_img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context,News_Single_Post.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra("source_url",news_items.get(position).getImage_url());
intent.putExtra("rendered", news_items.get(position).getTitle());
intent.putExtra("date",news_items.get(position).getNews_date());
intent.putExtra("content",news_items.get(position).getNews_content());
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return news_items.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView title;
public TextView news_date;
public ImageView news_img;
public ViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.news_title);
news_date = (TextView) itemView.findViewById(R.id.news_date);
news_img = (ImageView) itemView.findViewById(R.id.news_image);
}
}
}
private boolean loading = true;
int pastVisiblesItems, visibleItemCount, totalItemCount;
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener()
{
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy)
{
if(dy > 0) //check for scroll down
{
visibleItemCount = mLayoutManager.getChildCount();
totalItemCount = mLayoutManager.getItemCount();
pastVisiblesItems = mLayoutManager.findFirstVisibleItemPosition();
if (loading)
{
if ( (visibleItemCount + pastVisiblesItems) >= totalItemCount)
{
loading = false;
Log.v("...", "Last Item Wow !");
//Do pagination.. i.e. fetch new data
}
}
}
}
});
Don't forget to add
LinearLayoutManager mLayoutManager;
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);

ArrayAdapter and retrofit 2.0

How can I make this Adapter working with retrofit 2.0?
I mean in MainActivity
MainActivity.java
public class MainActivity extends AppCompatActivity {
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
Retrofit retrofit = new Retrofit.Builder().baseUrl("http://10.0.2.2/alruthea").build();
final TelService service = retrofit.create(TelService.class);
service.getphones(new Callback<List<tel_list>>() {
#Override
public void onResponse(Response<List<tel_list>> response, Retrofit retrofit) {
ArrayAdapter adapter = new ArrayAdapter(MainActivity.this, Telephones);
listView.setAdapter(adapter);
}
#Override
public void onFailure(Throwable t) {
}
}
);
}
}
TelService.java
public interface TelService {
#GET("/getphones.php")
retrofit.Call<List<tel_list>> getphones();
}
tel_list.java
public class tel_list{
private String name;
private String number;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
}
TelAdapter.java
public class TelAdapter extends ArrayAdapter<tel_list>{
Context context;
public TelAdapter(Context context, int resource, ArrayList<tel_list> users){
super(context, resource, users);
this.context = context;
}
#Override
public View getView(int position, View cell, ViewGroup parent){
Holder holder;
if (cell == null) {
holder = new Holder();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
cell = inflater.inflate(R.layout.list_item, null);
holder.textview = (TextView) cell.findViewById(R.id.names);
holder.textview1 = (TextView) cell.findViewById(R.id.numbers);
cell.setTag(holder);
}else {
holder = (Holder)cell.getTag();
}
tel_list user = getItem(position);
holder.textview.setText(user.getName());
holder.textview1.setText(user.getNumber());
return cell;
}
private class Holder{
TextView textview;
TextView textview1;
}
}
and about TelAdapter.class do I to write private class Holder or static class Holder?
Did you try it:
#Override
public void onResponse(Response<List<tel_list>> response, Retrofit retrofit) {
if (!response.isSuccess()) {
//TODO
return;
}
List<tel_list> date = response.body();
ArrayAdapter adapter = new ArrayAdapter(MainActivity.this, date);
listView.setAdapter(adapter);
}
The solution Patrick provided is correct. Just that you need 1 more resource parameter for the ArrayAdapter. This should work.
#Override
public void onResponse(Response<List<tel_list>> response, Retrofit retrofit) {
if (!response.isSuccess()) {
//TODO
return;
}
List<tel_list> date = response.body();
ArrayAdapter adapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, date);
listView.setAdapter(adapter);
}

Categories