Parsing JSON data & Load it in Fragments - java

Excuse me i already had an Application which Display my Sites articles and Novels in Android the codes in Main Activity to display only one Section
i create in the site 5 sections every section had a different content
i Added items to Navigation Drawers and i defined the fragment and its connectivity but the Problem in the Code i failed so
i want to know how to load Data in 4 Fragments
RecyclerViewAdapter.class
import android.content.Context;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private int previousPosition = 0;
private List<com.salim3dd.recyclerview_moredata.List_Item> List_Item;
private Context context;
public RecyclerViewAdapter(List<List_Item> list_Item, Context context) {
List_Item = list_Item;
this.context = context;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View menu1 = LayoutInflater.from(viewGroup.getContext()).inflate(
R.layout.row_item, viewGroup, false);
return new MenuItemViewHolder(menu1);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
MenuItemViewHolder menuItemHolder = (MenuItemViewHolder) holder;
menuItemHolder.TextName.setText(List_Item.get(position).getStory());
Picasso.with(context).load(List_Item.get(position).getImg_link()).into(menuItemHolder.imageView);
menuItemHolder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, List_Item.get(position).getStory(), Toast.LENGTH_SHORT).show();
}
});
if (position > previousPosition) { //scrolling DOWN
AnimationUtil.animate(menuItemHolder, true);
} else { // scrolling UP
AnimationUtil.animate(menuItemHolder, false);
}
previousPosition = position;
}
#Override
public int getItemCount() {
return (null != List_Item ? List_Item.size() : 0);
}
protected class MenuItemViewHolder extends RecyclerView.ViewHolder {
private CardView cardView;
private ImageView imageView;
private TextView TextName;
public MenuItemViewHolder(View view) {
super(view);
cardView = (CardView) view.findViewById(R.id.cardView);
imageView = (ImageView) view.findViewById(R.id.imageView);
TextName = (TextView) view.findViewById(R.id.TextName);
}
}
}
MainActivity
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.salim3dd.recyclerview_moredata.CheckInternetConnection;
import com.salim3dd.recyclerview_moredata.List_Item;
import com.salim3dd.recyclerview_moredata.R;
import com.salim3dd.recyclerview_moredata.RecyclerViewAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerViewAdapter recyclerView_dAdapter;
public List<List_Item> listItem = new ArrayList<>();
private GridLayoutManager gridLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.m_RecyclerView);
recyclerView.setHasFixedSize(true);
gridLayoutManager = new GridLayoutManager(this, 1);
recyclerView.setLayoutManager(gridLayoutManager);
recyclerView_dAdapter = new RecyclerViewAdapter(listItem, this);
recyclerView.setAdapter(recyclerView_dAdapter);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if (gridLayoutManager.findLastCompletelyVisibleItemPosition() == listItem.size() - 1) {
Get_All_Users(listItem.get(listItem.size()-1).getId());
}
}
});
Get_All_Users(0);
}
public void Get_All_Users(int limit) {
CheckInternetConnection cic = new CheckInternetConnection(getApplicationContext());
Boolean Ch = cic.isConnectingToInternet();
if (!Ch) {
Toast.makeText(this, R.string.no_internet_connection, Toast.LENGTH_SHORT).show();
} else {
StringRequest stringRequest = new StringRequest(Request.Method.GET,
"Data Link" + limit
,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonResponse = jsonArray.getJSONObject(0);
JSONArray jsonArray_usersS = jsonResponse.getJSONArray("All_storys");
for (int i = 0; i < jsonArray_usersS.length(); i++) {
JSONObject responsS = jsonArray_usersS.getJSONObject(i);
int id = responsS.getInt("id");
String story = responsS.getString("story_name");
String img_link = responsS.getString("img_link");
listItem.add(new List_Item(id, story, img_link));
}
recyclerView_dAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(stringRequest);
stringRequest.setShouldCache(false);
}
}
}
List Items.class
public class List_Item {
public int id;
public String story;
public String img_link;
public List_Item(int id, String story, String img_link) {
this.id = id;
this.story = story;
this.img_link = img_link;
}
public int getId() {
return id;
}
public String getStory() {
return story;
}
public String getImg_link() {
return img_link;
}
public void setId(int id) {
this.id = id;
}
}

Related

Calculating Price * Quantity from Adapter to Total Price from Activity

I want to get total price in Activity from Price and Quantity in Adapter, it's mean like qty * price = total_price.
Here is my Adapter for handling the list of Items Activity:
package com.example.aulaherbalfinal.Adapter;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.aulaherbalfinal.Model.DataModel;
import com.example.aulaherbalfinal.R;
import java.text.NumberFormat;
import java.util.List;
import java.util.Locale;
public class AdapterDataPembelian extends RecyclerView.Adapter<AdapterDataPembelian.HolderDataPembelian>{
private Context ctx;
private List<DataModel> listDataPembelian;
private int count;
public AdapterDataPembelian(Context ctx, List<DataModel> listDataPembelian) {
this.ctx = ctx;
this.listDataPembelian = listDataPembelian;
}
#NonNull
#Override
public HolderDataPembelian onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View layout = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_item_pembelian, parent, false);
HolderDataPembelian holder = new HolderDataPembelian(layout);
return holder;
}
#Override
public void onBindViewHolder(#NonNull HolderDataPembelian holder, int position) {
DataModel dm = listDataPembelian.get(position);
holder.tvId.setText(String.valueOf(dm.getId()));
holder.tvBarang.setText(dm.getBarang());
holder.tvStok.setText("Stok : "+String.valueOf(dm.getStok()));
holder.tvHarga.setText(formatRupiah(Double.parseDouble(String.valueOf(dm.getHarga()))));
holder.jmlBarang.setText(String.valueOf(dm.getQuantity()));
//holder.totalHarga.setText(String.valueOf(dm.getTotalHarga()));
Intent intent = new Intent("custom-message");
holder.btnRemove.setOnClickListener(v -> {
minusCartItem(holder,listDataPembelian.get(position));
});
holder.btnAdd.setOnClickListener(v -> {
plusCartItem(holder,listDataPembelian.get(position));
});
}
private void plusCartItem(HolderDataPembelian holder, DataModel dataModel) {
dataModel.setQuantity(dataModel.getQuantity()+1);
//dataModel.setTotalHarga(Integer.parseInt(String.valueOf(dataModel.getQuantity()*Double.parseDouble(String.valueOf(dataModel.getHarga())))));
holder.jmlBarang.setText(new StringBuilder().append(dataModel.getQuantity()));
}
private void minusCartItem(HolderDataPembelian holder, DataModel dataModel) {
if (dataModel.getQuantity() > 0){
dataModel.setQuantity(dataModel.getQuantity()-1);
//dataModel.setTotalHarga(Integer.parseInt(String.valueOf(dataModel.getQuantity()*Double.parseDouble(String.valueOf(dataModel.getHarga())))));
holder.jmlBarang.setText(new StringBuilder().append(dataModel.getQuantity()));
} else {
holder.jmlBarang.setText("0");
}
}
#Override
public int getItemCount() {
return listDataPembelian.size();
}
public class HolderDataPembelian extends RecyclerView.ViewHolder {
TextView tvId, tvBarang, tvStok, tvHarga;
Button btnAdd, btnRemove;
TextView jmlBarang, totalHarga;
public HolderDataPembelian(#NonNull View itemView) {
super(itemView);
tvId = itemView.findViewById(R.id.tv_id);
tvBarang = itemView.findViewById(R.id.tv_barang);
tvStok = itemView.findViewById(R.id.tv_stok);
tvHarga = itemView.findViewById(R.id.tv_harga);
btnAdd = itemView.findViewById(R.id.btn_add);
btnRemove = itemView.findViewById(R.id.btn_remove);
jmlBarang = itemView.findViewById(R.id.jml_barang);
totalHarga = itemView.findViewById(R.id.total_harga);
}
}
private String formatRupiah(Double number){
Locale localeID = new Locale("IND", "ID");
NumberFormat numberFormat = NumberFormat.getCurrencyInstance(localeID);
String formatRupiah = numberFormat.format(number);
String[] split = formatRupiah.split(",");
int length = split[0].length();
return split[0].substring(0,2)+". "+split[0].substring(2,length);
}
public int getTotalPrice(){
int totalPrice = 0;
for (int i=0 i<listDataPembelian.size(); i++){
}
}
}
And here is my Activity
package com.example.aulaherbalfinal.Activity;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.aulaherbalfinal.API.APIRequestData;
import com.example.aulaherbalfinal.API.RetroServer;
import com.example.aulaherbalfinal.Adapter.AdapterDataPembelian;
import com.example.aulaherbalfinal.Model.DataModel;
import com.example.aulaherbalfinal.Model.ResponseModel;
import com.example.aulaherbalfinal.R;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class PembelianActivity extends AppCompatActivity {
private RecyclerView rvData;
private RecyclerView.Adapter adData;
private RecyclerView.LayoutManager lmData;
private List<DataModel> listDataPembelian = new ArrayList<>();
private SwipeRefreshLayout srlData;
private ProgressBar pbData;
private TextView totalHarga;
private EditText jmlBarang;
#SuppressLint("ClickableViewAccessibility")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pembelian);
rvData = findViewById(R.id.rv_data);
lmData = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
rvData.setLayoutManager(lmData);
srlData = findViewById(R.id.srl_data);
pbData = findViewById(R.id.pb_data);
totalHarga = findViewById(R.id.total_harga);
jmlBarang = findViewById(R.id.jml_barang);
totalHarga = findViewById(R.id.total_harga);
//retrieveData();
CardView cvTotal = findViewById(R.id.cv_total);
rvData.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_MOVE){
cvTotal.setVisibility(View.INVISIBLE);
}
if (event.getAction() == MotionEvent.ACTION_UP){
cvTotal.setVisibility(View.VISIBLE);
}
return false;
}
});
BottomNavigationView bottom_navigation = findViewById(R.id.bottom_navigation);
bottom_navigation.setItemIconTintList(null);
bottom_navigation.setSelectedItemId(R.id.navigation_pembelian);
ImageView profile =findViewById(R.id.profile);
profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(PembelianActivity.this, ProfileActivity.class);
startActivity(intent);
finish();
}
});
bottom_navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch ( (item.getItemId())){
case R.id.navigation_stok:
startActivity(new Intent(getApplicationContext(), MainActivity.class));
overridePendingTransition(0, 0);
return true;
case R.id.navigation_pembelian:
return true;
case R.id.navigation_penjualan:
startActivity(new Intent(getApplicationContext(), PenjualanActivity.class));
overridePendingTransition(0, 0);
return true;
}
return false;
}
});
srlData.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
srlData.setRefreshing(true);
retrieveData();
srlData.setRefreshing(false);
}
});
}
#Override
protected void onResume() {
super.onResume();
retrieveData();
}
public void retrieveData(){
pbData.setVisibility(View.VISIBLE);
APIRequestData ardData = RetroServer.konekRetrofit().create(APIRequestData.class);
Call<ResponseModel> tampildata = ardData.ardRetrieveData();
tampildata.enqueue(new Callback<ResponseModel>() {
#Override
public void onResponse(Call<ResponseModel> call, Response<ResponseModel> response) {
int kode = response.body().getKode();
String pesan = response.body().getPesan();
//Toast.makeText(MainActivity.this, "Kode : "+kode+" | Pesan : "+pesan, Toast.LENGTH_SHORT).show();
listDataPembelian = response.body().getData();
adData = new AdapterDataPembelian(PembelianActivity.this, listDataPembelian);
rvData.setAdapter(adData);
adData.notifyDataSetChanged();
pbData.setVisibility(View.INVISIBLE);
}
#Override
public void onFailure(Call<ResponseModel> call, Throwable t) {
Toast.makeText(PembelianActivity.this, "Gagal Menghubungi Server", Toast.LENGTH_SHORT).show();
pbData.setVisibility(View.INVISIBLE);
}
});
}
}
Here is my app
I would do something like this:
Create an Interface for your activity to implement:
public interface CallbackIF {
double tally(double amount, int quantity)
}
public class PembelianActivity extends AppCompatActivity implements CallbackIF {
#Override
public double tally(double amount, int quantity) {
return amount * quantity;
}
}
Then when you initialize your recyclerview adapter pass in the interface like so:
adData = new AdapterDataPembelian(PembelianActivity.this, listDataPembelian, PembelianActivity.this);
And change your constructor for the data adapter to be
private CallbackIF callback;
public AdapterDataPembelian(Context ctx, List<DataModel> listDataPembelian, CallbackIF callback) {
this.ctx = ctx;
this.listDataPembelian = listDataPembelian;
this.callback = callback;
}
Then in your onClicklistener for your list / wherever you want to trigger a tally just call
double value = callback.tally(amount, quantity);
If you have any questions please ask

Data is not binding to android recyclerview

I am new to android. I am trying to download data using the Github api and display in and infinite scrolling RecyclerView, the JSON data is been parsed, but somehow the data is not been attached to the recyclerview.
Here is the code below:
Developer_RV_Adapter.java
package com.davidshare.githubdevelopers;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.List;
/**
* Created by GemShare on 9/6/2017.
*/
public class Developer_RV_Adapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final int VIEW_TYPE_ITEM = 0;
private final int VIEW_TYPE_LOADING = 1;
private OnLoadMoreListener mOnLoadMoreListener;
private boolean isLoading;
private int visibleThreshold = 10;
private int lastVisibleItem, totalItemCount;
private List<Developer> developerList;
Context context;
RecyclerView recyclerView;
public Developer_RV_Adapter(Context context, List<Developer> developerList, RecyclerView recyclerView) {
this.developerList = developerList;
this.context = context;
this.recyclerView = recyclerView;
final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
totalItemCount = linearLayoutManager.getItemCount();
lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
if(!isLoading && totalItemCount<=(lastVisibleItem+visibleThreshold)){
if(mOnLoadMoreListener!=null){
mOnLoadMoreListener.onLoadMore();
}
isLoading = true;
}
}
});
}
public void setmOnLoadMoreListener(OnLoadMoreListener mOnLoadMoreListener){
this.mOnLoadMoreListener = mOnLoadMoreListener;
}
#Override
public int getItemViewType(int position){
return developerList.get(position) == null? VIEW_TYPE_LOADING : VIEW_TYPE_ITEM;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if(viewType == VIEW_TYPE_ITEM){
View developerView = LayoutInflater.from(context).inflate(R.layout.developer_list_item, parent, false);
return new DeveloperViewHolder(developerView);
}else if(viewType== VIEW_TYPE_LOADING){
View loadingView = LayoutInflater.from(context).inflate(R.layout.progress_bar_item, parent, false);
return new ProgressViewHolder(loadingView);
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
Log.w("binder function", "Just entered the binder");
Developer developer = developerList.get(position);
if(holder instanceof DeveloperViewHolder){
DeveloperViewHolder developerViewHolder = (DeveloperViewHolder) holder;
developerViewHolder.gitNameTv.setText(developer.getGitUsername());
Log.w("binder ", developer.getGitProfileUrl());
developerViewHolder.gitUrlTv.setText(developer.getGitProfileUrl());
developerViewHolder.gitPicUrlTv.setText(developer.getGitProfilePicUrl());
Log.w("profile pic", developer.getGitProfilePicUrl());
Picasso.with(developerViewHolder.gitNameTv.getContext()).load(developer.getGitProfilePicUrl()).transform(new RoundedImage(2)).fit().centerCrop().into(developerViewHolder.profilePicImgV);
}else if (holder instanceof ProgressViewHolder) {
ProgressViewHolder loadingViewHolder = (ProgressViewHolder) holder;
loadingViewHolder.loadingProgress.setIndeterminate(true);
}
}
#Override
public int getItemCount() {
return developerList == null ? 0 : developerList.size();
}
public void setLoaded() {
isLoading = false;
}
public class DeveloperViewHolder extends RecyclerView.ViewHolder{
TextView gitNameTv;
TextView gitUrlTv;
ImageView profilePicImgV;
TextView gitPicUrlTv;
public DeveloperViewHolder(final View itemView) {
super(itemView);
gitNameTv = (TextView) itemView.findViewById(R.id.developerName);
gitUrlTv = (TextView) itemView.findViewById(R.id.developerUrl);
profilePicImgV = (ImageView) itemView.findViewById(R.id.developerPic);
gitPicUrlTv = (TextView) itemView.findViewById(R.id.developerPicUrl);
itemView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
Intent i = new Intent(itemView.getContext(), Profile.class);
i.putExtra("profile_name", gitNameTv.getText().toString());
i.putExtra("profile_url", gitUrlTv.getText().toString());
i.putExtra("profile_pic_url", gitPicUrlTv.getText().toString());
v.getContext().startActivity(i);
}
});
}
}
public static class ProgressViewHolder extends RecyclerView.ViewHolder{
public ProgressBar loadingProgress;
public ProgressViewHolder(View itemView) {
super(itemView);
loadingProgress = (ProgressBar) itemView.findViewById(R.id.loading_progress_bar);
}
}
}
DeveloperList.java
package com.davidshare.githubdevelopers;
import android.app.ProgressDialog;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class DeveloperList extends AppCompatActivity {
List<Developer> developerList;
Developer_RV_Adapter developer_rv_adapter;
Developer developer;
RecyclerView developerRV;
private static final String GIT_BASE_URL = "https://api.github.com/search/users?q=location:";
private static int page = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_developer_list);
developerRV = (RecyclerView) findViewById(R.id.developer_rv);
developerRV.setLayoutManager(new LinearLayoutManager(this));
developerList = new ArrayList<>();
getDevelopersData(prepareQuery("java", "lagos", page));
developer_rv_adapter = new Developer_RV_Adapter(DeveloperList.this, developerList, developerRV);
developerRV.setAdapter(developer_rv_adapter);
developer_rv_adapter.setmOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
developerList.add(null);
developer_rv_adapter.notifyItemInserted(developerList.size()-1);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
developerList.remove(developerList.size()-1);
developer_rv_adapter.notifyItemRemoved(developerList.size());
getDevelopersData(prepareQuery("java", "lagos", page));
developer_rv_adapter.notifyDataSetChanged();
developer_rv_adapter.setLoaded();
}
}, 5000);
}
});
}
the getDevelopersData method uses volley to query the github api and parse the JSON response into a List
public void getDevelopersData(String requestUrl) {
StringRequest jsonSringRequest = new StringRequest(Request.Method.GET, requestUrl, new Response.Listener<String>() {
#Override
public void onResponse(String jsonResponse) {
try {
JSONObject gitJSONOBject = new JSONObject(jsonResponse);
JSONArray gitItemsArray = gitJSONOBject.getJSONArray("items");
for (int i = 0; i < gitItemsArray.length(); i++) {
JSONObject developerObject = gitItemsArray.getJSONObject(i);
developer = new Developer(developerObject.getString("login"),
developerObject.getString("html_url"),
developerObject.getString("avatar_url"));
developerList.add(developer);
Log.w("developer_data ", developer.getGitUsername());
}
Log.w("JSON DATA", "getting the json data");
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.e("Volley error", volleyError.getMessage());
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonSringRequest);
}
//get the location and language and the page of the api data you want to load
private String prepareQuery(String language, String location, int page){
this.page++;
String queryUrl = GIT_BASE_URL+location+"+language:"+language+"&page="+page+"&per_page=50";
Log.w("Query URL = > ", queryUrl);
return queryUrl;
}
}
Can anyone help me with this?
try to notify adapter in getDevelopersData() after data add to array list like add this line developer_rv_adapter.notifyDataSetChanged();
Instead of notifyItemInserted() inserted use
notifyItemRangedChanged(fromIndex,toIndex);
This will notify the adapter that some set of data is changed among the whole data and it tells the adapter that adapter should refresh the data and reload it into the recyclerView starting from fromIndex to toIndex as passed into the method.
If all data are changed then use :
notifyDataSetChanged();
if only one dataItem is changed then use :
notifyItemChanged(dataPosition);
Also I think this statment is causing problem.Try to remove this statment and check again.
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
developerList.remove(developerList.size()-1);
developer_rv_adapter.notifyItemRemoved(developerList.size());
getDevelopersData(prepareQuery("java", "lagos", page));
developer_rv_adapter.notifyDataSetChanged();
developer_rv_adapter.setLoaded();
}
}, 5000);
The problem was resolved by just adding developer_rv_adapter.notifyDataSetChanged(); just below developerList.add(developer); this notifies the adapter that new items have been added to the list.

Blank Screen Shows after search from database (Android)

When i tap search donor then it shows blank screen in listview i don't know why This is the response that i get back from server
This is my custom adapter code:
package com.example.kamran.ebloodbank;
import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;
/**
* Created by Kamran on 4/12/2017.
*/
public class DonorAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<DataSet> donorItems;
public DonorAdapter(Activity activity,List<DataSet> donorItems) {
this.activity = activity;
this.donorItems = donorItems;
}
#Override
public int getCount() {
return donorItems.size();
}
#Override
public Object getItem(int location) {
return donorItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.donor_search_list_theme, null);
TextView nameTextView = (TextView) convertView.findViewById(R.id.donor_name);
TextView areaTextView = (TextView) convertView.findViewById(R.id.donor_area);
DataSet d = donorItems.get(position);
nameTextView.setText(d.getName());
areaTextView.setText(d.getArea());
return convertView;
}
}
This is my model code:
package com.example.kamran.ebloodbank;
import android.widget.ArrayAdapter;
import java.util.ArrayList;
/**
* Created by Kamran on 4/12/2017.
*/
public class DataSet {
private String name;
private int area;
public void setArea(int area) {
this.area = area;
}
public void setName(String name) {
this.name = name;
}
public int getArea() {
return area;
}
public String getName() {
return name;
}
}
This is my first activity code:
package com.example.kamran.ebloodbank;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.kamran.ebloodbank.data.BloodContract.BloodEntry;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class FindDonor extends AppCompatActivity {
Spinner bloodgroup;
Spinner area;
String findDonorUrl = "https://wwwkamranalitk.000webhostapp.com/findDonor.php";
int mBlood = BloodEntry.BLOOD_GROUP_A_POS;
int mArea = BloodEntry.DONOR_AREA_MALIR;
Button searchButton;
RequestQueue requestQueue;
StringRequest request;
JSONObject jsonObject;
JSONArray result;
private List<DataSet> donorList = new ArrayList<DataSet>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_donor);
bloodgroup = (Spinner) findViewById(R.id.bloodspinnerfinddonor);
area = (Spinner) findViewById(R.id.areaSpinner);
searchButton = (Button) findViewById(R.id.searchDonor);
setupSpinnerBlood();
setupSpinnerArea();
requestQueue = Volley.newRequestQueue(getApplicationContext());
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
request = new StringRequest(Request.Method.POST, findDonorUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
jsonObject = new JSONObject(response);
result = jsonObject.getJSONArray("result");
JSONObject donorData = result.getJSONObject(0);
DataSet donorSet = new DataSet();
donorSet.setName(donorData.getString("name"));
donorSet.setArea(donorData.getInt("area"));
donorList.add(donorSet);
Intent intent = new Intent(FindDonor.this, DonorSearchList.class);
startActivity(intent);
finish();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String,String> parameters = new HashMap<String, String>();
parameters.put("bloodgroup", String.valueOf(mBlood));
parameters.put("area", String.valueOf(mArea));
return parameters;
}
};
requestQueue.add(request);
}
});
}
private void setupSpinnerBlood() {
ArrayAdapter bloodGroupSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.blood_group, android.R.layout.simple_spinner_item);
bloodGroupSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
bloodgroup.setAdapter(bloodGroupSpinnerAdapter);
bloodgroup.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selection = (String) parent.getItemAtPosition(position);
if (!TextUtils.isEmpty(selection)) {
if (selection.equals(getString(R.string.blood_apos))) {
mBlood = BloodEntry.BLOOD_GROUP_A_POS;
} else if (selection.equals((getString(R.string.blood_bpos)))) {
mBlood = BloodEntry.BLOOD_GROUP_B_POS;
} else if (selection.equals(getString(R.string.blood_opos))) {
mBlood = BloodEntry.BLOOD_GROUP_O_POS;
} else if (selection.equals((getString(R.string.blood_oneg)))) {
mBlood = BloodEntry.BLOOD_GROUP_O_NEG;
}
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
mBlood = BloodEntry.BLOOD_GROUP_A_POS;
}
});
}
private void setupSpinnerArea() {
ArrayAdapter areaSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.area, android.R.layout.simple_spinner_item);
areaSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
area.setAdapter(areaSpinnerAdapter);
area.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selection = (String) parent.getItemAtPosition(position);
if (!TextUtils.isEmpty(selection)) {
if (selection.equals(getString(R.string.donor_area_malir))) {
mArea = BloodEntry.DONOR_AREA_MALIR;
} else if (selection.equals(getString(R.string.donor_area_defence))) {
mArea = BloodEntry.DONOR_AREA_DEFENCE;
} else if (selection.equals(getString(R.string.donor_area_korangi))) {
mArea = BloodEntry.DONOR_AREA_KORANGI;
} else if (selection.equals(getString(R.string.donor_area_johar))) {
mArea = BloodEntry.DONOR_AREA_JOHAR;
}
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
mArea = BloodEntry.DONOR_AREA_MALIR;
}
});
}
}
and This is the code in which data will be shown:
package com.example.kamran.ebloodbank;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class DonorSearchList extends AppCompatActivity {
private String mArea;
private List<DataSet> donorList = new ArrayList<DataSet>();
private ListView listView;
private DonorAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_donor_search_list);
listView = (ListView) findViewById(R.id.donorListView);
adapter = new DonorAdapter(this, donorList);
listView.setAdapter(adapter);
}
}
You need to transfer data from the search to list activity.
Try something like this:
public class bridge {
public static List<DataSet> donorList = new ArrayList<DataSet>();
}
Then, in the class FindDonor:
donorSet.setName(donorData.getString("name"));
donorSet.setArea(donorData.getInt("area"));
donorList.add(donorSet);
//here put this line
bridge.donarList = donarList;
//rest code
Intent intent = new Intent(FindDonor.this, DonorSearchList.class);
Then, in the DonorSearchList class:
adapter = new DonorAdapter(this, bridge.donorList);

Populate recycle adapter from controller class

I'm trying to populate a recycle adapter from a controller class, to split the logic in the app. But I can't seem to get it working.. Do to the request is running on another thread, the view is not updated before it is shown. What am I doing wrong ?
FragmentClass:
package lassebjoerklund.homecontrol.views.fragments;
import android.app.Fragment;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import org.json.JSONArray;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import lassebjoerklund.homecontrol.R;
import lassebjoerklund.homecontrol.adapters.FridgeFragmentOverViewAdapter;
import lassebjoerklund.homecontrol.controllers.FridgeController;
import lassebjoerklund.homecontrol.decorations.DividerItemDecoration;
import lassebjoerklund.homecontrol.model.Product;
import lassebjoerklund.homecontrol.utils.FragmentUtil;
/**
* Created by zigge on 29-Mar-16.
*/
public class FridgeFragmentOverView extends Fragment {
private final FridgeController fridgeController = new FridgeController();
private RecyclerView recyclerView;
private LinkedList<String> types;
private FridgeFragmentOverViewAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_overview_layout, container, false);
recyclerView = (RecyclerView) v.findViewById(R.id.productOverviewRecycleView);
recyclerView.setHasFixedSize(true);
RecyclerView.ItemDecoration itemDecoration = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST);
recyclerView.addItemDecoration(itemDecoration);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
adapter = new FridgeFragmentOverViewAdapter(fridgeController.getProductsTypes());
recyclerView.setAdapter(adapter);
return v;
}
#Override
public void onResume() {
super.onResume();
fridgeController.refresh(getContext(), adapter);
}
}
Controller Class:
package lassebjoerklund.homecontrol.controllers;
import android.content.Context;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import lassebjoerklund.homecontrol.adapters.FridgeFragmentOverViewAdapter;
import lassebjoerklund.homecontrol.interfaces.OnSucsess;
import lassebjoerklund.homecontrol.model.Product;
/**
* Created by zigge on 29-Mar-16.
*/
public class FridgeController implements OnSucsess {
private RequestQueue rQueue;
private ArrayList<Product> products;
private List<String> productsTypes;
public ArrayList<Product> getProducts() {
return products;
}
public List<String> getProductsTypes() {
return productsTypes;
}
public void refresh(Context context, final FridgeFragmentOverViewAdapter adapter) {
String fetchProducts = "http://87.52.28.25:900/index.php";
rQueue = Volley.newRequestQueue(context);
final JsonArrayRequest getProductsRequest = new JsonArrayRequest(fetchProducts, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
products = new ArrayList<>();
productsTypes = new ArrayList<>();
try {
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = (JSONObject) response.get(i);
String barcode = jsonObject.getString("code");
String name = jsonObject.getString("name");
String ex_date = jsonObject.getString("ex_date");
String add_date = jsonObject.getString("add_date");
String type = jsonObject.getString("type");
Product product = new Product(barcode, name, ex_date, add_date, type);
products.add(product);
}
} catch (JSONException e) {
e.printStackTrace();
}
if (products.size() != 0) {
for (int i = 0; i < products.size(); i++) {
if (!productsTypes.contains(products.get(i).getType())) {
productsTypes.add(products.get(i).getType());
}
}
}
getProductsOnsucsess(adapter);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
rQueue.add(getProductsRequest);
}
#Override
public void getProductsOnsucsess(FridgeFragmentOverViewAdapter adapter) {
adapter.refreshAdapter(productsTypes);
}
}
Adapter:
package lassebjoerklund.homecontrol.adapters;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import lassebjoerklund.homecontrol.R;
import lassebjoerklund.homecontrol.model.Product;
/**
* Created by zigge on 29-Mar-16.
*/
public class FridgeFragmentOverViewAdapter extends RecyclerView.Adapter {
private List<String> types;
public FridgeFragmentOverViewAdapter(List<String> types) {
this.types = types;
}
#Override
public int getItemCount() {
return 0;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_overview_card_layout, null);
return new ProductsGroupedHolder(v);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
}
public class ProductsGroupedHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView tvTypeOfProduct, tvCount, tvExpired;
public ProductsGroupedHolder(View itemView) {
super(itemView);
tvTypeOfProduct = (TextView) itemView.findViewById(R.id.tvTypeOfProduct);
tvCount = (TextView) itemView.findViewById(R.id.tvCount);
tvExpired = (TextView) itemView.findViewById(R.id.tvExpired);
}
#Override
public void onClick(View v) {
}
}
public void refreshAdapter(List<String> types) {
if(this.types != null) {
this.types.clear();
this.types = types;
notifyDataSetChanged();
}else {
this.types = types;
notifyDataSetChanged();
}
}
}
Try calling:
adapter.notifyDataSetChanged();
after updating it.
Edit 1:
Return actual size of adapter items in getItemCount() as #prathamkesarkar said.
Simple looks like you have set the getItemType() method return 0.
That method determines how much item your RecyclerView have.
#Override
public int getItemCount() {
return type.size();
}

Periodic Error with CardView and RecycleView

I have this weird periodic error, when i boot the app, and the onCreate is called, but the CardView is not showing anything. Other times I do the exact same thing, booting the app, and the CardView is showing exactly what it should.
I can't seem to find the error..
The main class:
package lassebjoerklund.easyfridge;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class BootActivity extends Activity {
//TODO Make get method for table with barcode.
//TODO Update postRequest so that it macthes the barcode to the database, and getting a json object. object -> toString
private ArrayList<Products> productsToDisplayInlist;
private String TAG = BootActivity.class.getSimpleName();
private String getDataurl = "http://XXX.XXX.XXX.XXX/selectAll.php";
private static String insertDataUrl = "http://XXX.XXX.XXX.XXX/insertAll.php";
private JsonArrayRequest jsonArrayRequest;
private RecyclerView.Adapter mAdapter;
private String jsonRespons = "";
private static RequestQueue rQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
//Layout
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_boot_layout);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.cardList);
recyclerView.setHasFixedSize(false);
recyclerView.setLayoutManager(linearLayoutManager);
//RequestQueue
rQueue = Volley.newRequestQueue(this);
productsToDisplayInlist = new ArrayList<>();
getRequest();
Log.d(TAG, productsToDisplayInlist.toString());
mAdapter = new ProductCardAdapter(productsToDisplayInlist);
recyclerView.setAdapter(mAdapter);
//Intent to switch to activity
//final Intent dispalyProductsIntent = new Intent(BootActivity.this, ProductViewController.class);
//final Intent scanBarcodeIntent = new Intent(BootActivity.this, BarcodeTracking.class);
//final ImageButton updateViewButton = (ImageButton) findViewById(R.id.bViewProducts);
/*updateViewButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(dispalyProductsIntent);
}
});*/
/* final ImageButton addNewEntry = (ImageButton) findViewById(R.id.addEntry);
addNewEntry.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
startActivity(scanBarcodeIntent);
}
});*/
}
#Override
protected void onResume() {
Log.d("onResume", "onResume");
/*Toast toast = Toast.makeText(this, "onResume", Toast.LENGTH_LONG);
toast.show();*/
super.onResume();
}
#Override
protected void onRestart() {
Log.d("onRestart", "onRestart");
/*Toast toast = Toast.makeText(this, "onRestart", Toast.LENGTH_SHORT);
toast.show();*/
super.onRestart();
}
#Override
protected void onStop() {
Log.d("onStop", "onStop");
// productsToDisplayInlist.clear();
super.onStop();
}
#Override
protected void onPause() {
Log.d("onPause", "onPause");
super.onPause();
}
//TODO make error msg if there is no connection.
public void getRequest() {
productsToDisplayInlist.clear();
jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, getDataurl, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Log.d(TAG, response.toString());
try {
for (int i = 0; i < response.length(); i++) {
JSONObject productToBuild = (JSONObject) response.get(i);
jsonRespons = productToBuild.toString();
String barcode = productToBuild.getString("code");
String name = productToBuild.getString("name");
String type = productToBuild.getString("type");
int id = productToBuild.optInt("id");
String rmDate = productToBuild.getString("rm_date");
String exDate = productToBuild.getString("ex_date");
String placementDate = productToBuild.getString("add_date");
Products product = new Products(barcode, name, placementDate, exDate, rmDate, type);
productsToDisplayInlist.add(product);
Log.d("Product", product.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Volly", "Error");
error.printStackTrace();
}
});
rQueue.add(jsonArrayRequest);
}
public static void postRequest(final Products product) {
try {
StringRequest stringRequest = new StringRequest(Request.Method.POST, insertDataUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
VolleyLog.d("onResponse", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Volley insertData", "ERROR");
Log.d("error: ", error.getCause().toString());
error.printStackTrace();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> perameters = new HashMap<>();
perameters.put("barcode", product.getBarcode());
perameters.put("addDate", product.getDayOfadd());
perameters.put("exDate", product.getExDate());
return perameters;
}
};
rQueue.add(stringRequest);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Here I init the layout and add the adapter for the RecycleView. The productsToDisplayInList is populated in the getRequest() method. But somehow, it's only periodic getting populated..
Adapter class:
package lassebjoerklund.easyfridge;
import android.graphics.Color;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class ProductCardAdapter extends RecyclerView.Adapter<ProductHolder> {
private CardView cardView;
private List<Products> productses;
private Calendar c;
public ProductCardAdapter(ArrayList<Products> items) {
productses = items;
}
#Override
public int getItemCount() {
return productses.size();
}
#Override
public void onBindViewHolder(ProductHolder holder, int position) {
Products product = productses.get(position);
Date returnDate = Util.parseDateString(product.getExDate());
if (Util.getCurrentDate().after(returnDate)) {
cardView.setCardBackgroundColor(Color.parseColor("#FF000D"));
holder.cardName.setText(product.getName());
holder.cardAddDate.setText(product.getDayOfadd());
holder.cardExDate.setText(product.getExDate());
holder.cardType.setText(product.getType());
Log.d("Product Card", product.toString());
} else {
holder.cardName.setText(product.getName());
holder.cardAddDate.setText(product.getDayOfadd());
holder.cardExDate.setText(product.getExDate());
holder.cardType.setText(product.getType());
Log.d("Product Card", product.toString());
}
}
#Override
public ProductHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardlayout, parent, false);
cardView = new CardView(parent.getContext());
return new ProductHolder(itemView);
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
}
Holder Class:
package lassebjoerklund.easyfridge;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
public class ProductHolder extends RecyclerView.ViewHolder {
protected TextView cardName;
protected TextView cardAddDate;
protected TextView cardExDate;
protected TextView cardType;
public ProductHolder(View itemView) {
super(itemView);
cardName = (TextView) itemView.findViewById(R.id.cardName);
cardAddDate = (TextView) itemView.findViewById(R.id.cardAddDate);
cardExDate = (TextView) itemView.findViewById(R.id.cardExDate);
cardType = (TextView) itemView.findViewById(R.id.cardType);
}
}

Categories

Resources