Pass JSON Array in RecyclerView Adapter Class to Activity Class - android

I have a RecyclerView and am creating a JSON Array with the ids of elements which are clicked in the onClick method. I am able to generate the JSON Array but I am facing trouble passing this JSON Array to my Activity.
I created an interface :
public interface ClientDataTransfer {
public void getValues(JSONArray jsonArray);
}
and modified the Adapter constructor like this:
public ClientListAdapter(List<ClientListData> clientListData, Context context, ClientDataTransfer clientDataTransfer) {
super();
this.clientListData = clientListData;
this.context = context;
this.clientDataTransfer = clientDataTransfer;
}
and in my Activity class I am setting the adapter like this:
recyclerViewAdapter = new ClientListAdapter(clientListData, this, this);
recyclerView.setAdapter(recyclerViewAdapter);
I implemented the Interface in the Activity class and inherited the method but I am facing trouble getting the JSON Array in the Activity class.
I am creating the JSON Array inside the setOnClickListener method in onBindViewHolder.
Here is my Adapter Class:
public class ClientListAdapter extends RecyclerView.Adapter<ClientListAdapter.ViewHolder> {
private Context context;
private List<ClientListData> clientListData;
public JSONArray clientArray = new JSONArray();
public ClientDataTransfer clientDataTransfer;
public ClientListAdapter(List<ClientListData> clientListData, Context context, ClientDataTransfer clientDataTransfer) {
super();
this.clientListData = clientListData;
this.context = context;
this.clientDataTransfer = clientDataTransfer;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.client_list_item, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(final ClientListAdapter.ViewHolder holder, final int position) {
final ClientListData clientListDataModel = clientListData.get(position);
holder.clientList.setText(clientListDataModel.getClientName());
holder.itemView.setBackgroundColor(clientListDataModel.isSelected() ? Color.GRAY : Color.WHITE);
holder.clientList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clientListDataModel.setSelected(!clientListDataModel.isSelected());
try {
JSONObject clientObject = new JSONObject();
if(clientListDataModel.isSelected()) {
holder.itemView.setBackgroundColor(Color.GRAY);
clientObject.put("id", clientListData.get(position).getClientId());
clientArray.put(clientObject);
} else if(!clientListDataModel.isSelected()) {
holder.itemView.setBackgroundColor(Color.WHITE);
for (int i = 0; i < clientArray.length(); i++) {
clientObject = clientArray.getJSONObject(i);
if (clientObject.getString("id").equals(clientListDataModel.getClientId())) {
clientArray=removeFromJsonArray(clientArray,i);
break;
}
}
}
//clientArray.put(clientObject);
} catch (JSONException e) {
e.printStackTrace();
}
clientDataTransfer.getValues(clientArray);
Log.e("client id array", ""+clientArray);
}
});
}
#Override
public int getItemCount() {
return clientListData == null ? 0:clientListData.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public TextView clientList;
public ViewHolder(View itemView) {
super(itemView);
clientList = (TextView) itemView.findViewById(R.id.tv_client_list);
}
}
private JSONArray removeFromJsonArray(JSONArray array,int position) {
JSONArray newArray = new JSONArray();
for (int i=0;i<array.length();i++)
{
//Excluding the item at position
if (i != position)
{
try {
newArray.put(array.get(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
return newArray;
}
}
holder.clientList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clientListDataModel.setSelected(!clientListDataModel.isSelected());
try {
JSONObject clientObject = new JSONObject();
if(clientListDataModel.isSelected()) {
holder.itemView.setBackgroundColor(Color.GRAY);
clientObject.put("id", clientListData.get(position).getClientId());
clientArray.put(clientObject);
} else if(!clientListDataModel.isSelected()) {
holder.itemView.setBackgroundColor(Color.WHITE);
for (int i = 0; i < clientArray.length(); i++) {
clientObject = clientArray.getJSONObject(i);
if (clientObject.getString("id").equals(clientListDataModel.getClientId())) {
clientArray=removeFromJsonArray(clientArray,i);
break;
}
}
}
//clientArray.put(clientObject);
} catch (JSONException e) {
e.printStackTrace();
}
clientDataTransfer.getValues(clientArray);
Log.e("client id array", ""+clientArray);
}
});
Here is my Activity Class where I am implementing the Adapter:
public class ClientListActivity extends AppCompatActivity implements View.OnClickListener, ClientDataTransfer {
private String groupId;
private String clientId;
private String clientName;
private RecyclerView recyclerView;
private List<ClientListData> clientListData;
private RecyclerView.LayoutManager recyclerViewLayoutManager;
private RecyclerView.Adapter recyclerViewAdapter;
private JSONArray clientArrayList = new JSONArray();
ClientDataTransfer clientDataTransferx;
private Toolbar toolbar;
private FloatingActionButton share;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client_list);
recyclerView = (RecyclerView) findViewById(R.id.rv_client_list);
toolbar = (Toolbar) findViewById(R.id.client_list_toolbar);
share = (FloatingActionButton) findViewById(R.id.floating_action_button);
share.setOnClickListener(this);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(ContextCompat.getColor(this, R.color.colorSecondary));
}
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
clientListData = new ArrayList<>();
recyclerViewLayoutManager = new LinearLayoutManager(this);
recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setLayoutManager(recyclerViewLayoutManager);
if(getIntent() != null) {
Bundle bundle = getIntent().getExtras();
try {
JSONObject jsonClientListObject = new JSONObject(getIntent().getStringExtra("clientList"));
JSONArray clientArray = jsonClientListObject.optJSONArray("activeClients");
for(int i = 0 ; i < clientArray.length(); i++) {
ClientListData clientListData = new ClientListData();
clientListData.setClientId(clientArray.getJSONObject(i).getString("id"));
clientListData.setClientName(clientArray.getJSONObject(i).getString("name"));
clientId = clientListData.getClientId();
clientName = clientListData.getClientName();
}
groupId = bundle.getString("groupId");
for(int i=0; i<clientArray.length(); i++) {
ClientListData clientListDataModel = new ClientListData();
JSONObject jsonObject = null;
jsonObject = clientArray.getJSONObject(i);
clientListDataModel.setClientName(jsonObject.getString("name"));
clientListDataModel.setClientId(jsonObject.getString("id"));
clientListData.add(clientListDataModel);
}
recyclerViewAdapter = new ClientListAdapter(clientListData, this, this);
recyclerView.setAdapter(recyclerViewAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
/*#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.select_all, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.select_all:
break;
}
return super.onOptionsItemSelected(item);
}*/
#Override
public void getValues(JSONArray jsonArray) {
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.floating_action_button:
clientDataTransferx = new ClientDataTransfer() {
#Override
public void getValues(JSONArray jsonArray) {
clientDataTransferx.getValues(clientArrayList);
}
};
break;
}
}
}

pass json object as a String
when you have to read use :-
JJSONObject obj = new JSONObject(Stringhere);
JSONArray jsonArray = obj.getJSONArray("results");
ArrayList < objectClass > somearray= new ArrayList < objectClass > ();
for (int i = 0; i < jsonArray.length(); i++)
{
Movie objectClass = new objectClass();
JSONObject json_data = jsonArray.getJSONObject(i);
somearray.setImageUrl(json_data.getString("key1"));
somearray.setTitle(json_data.getString("key2"));
somearray.setPlot(json_data.getString("key3"));
}

Related

How to get size of a particular variable from Model class in Android?

I have a model class:
public class Home_Model_ViewPager {
public String buttonLink;
public String tipsDescription;
public String tipsButton;
public Context context;
public Home_Model_ViewPager( Context context, String tipsDescription, String tipsButton, String buttonLink) {
this.context = context;
this.tipsDescription = tipsDescription;
this.tipsButton = tipsButton;
this.buttonLink = buttonLink;
}
public String getButtonLink() {
return buttonLink;
}
public void setButtonLink(String buttonLink) {
this.buttonLink = buttonLink;
}
public String getTipsDescription() {
return tipsDescription;
}
public void setTipsDescription(String tipsDescription) {
this.tipsDescription = tipsDescription;
}
public String getTipsButton() {
return tipsButton;
}
public void setTipsButton(String tipsButton) {
this.tipsButton = tipsButton;
}
}
I have used this model class to use it in viewpager adapter.
So, I am using a recyclerview and setting data to it. Now I have a problem that I have a viewpager in recycleritem. I want to return the size of viewpager adapter of any element in Home_Model_ViewPager as each element has diff size.
This is what I tried in ViewPagerAdapter:
public class ViewPagerAdapter extends PagerAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
List<Home_Model_ViewPager> totalList;
public ViewPagerAdapter(Context context, List<Home_Model_ViewPager> totalList) {
this.context = context;
this.totalList = totalList;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return totalList.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
// Declare Variables
TextView tricksDescription;
Button tricksButton;
View itemView = inflater.inflate(R.layout.viewpager_item, container,
false);
tricksDescription = itemView.findViewById(R.id.xtv_tricks_description);
tricksButton = itemView.findViewById(R.id.tricks_button);
tricksDescription.setText(Html.fromHtml(totalList.get(position).getTipsDescription()));
tricksButton.setText(Html.fromHtml(totalList.get(position).getTipsButton()));
tricksButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
String url = totalList.get(position).getButtonLink();
intent.setData(Uri.parse(url));
startActivity(intent);
}
catch (Exception e) {
e.printStackTrace();
}
}
});
container.addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
}
}
I am using volley to get the values as JSON..
private void Home() {
try {
if (getActivity()!=null)
Commonfunctions.LoadPreferences(getActivity());
System.out.println("Authtoken:" + Commonfunctions.Token_key);
appservice.View_All_Events(Commonfunctions.Token_key, String.valueOf(pagenumber), new Server_Callback() {
#Override
public void onSuccess(String response) {
System.out.println("HOME Response :" + response);
try {
JSONObject signObject = new JSONObject(response);
String resStatus = signObject.getString(AppConstants.STATUS);
String resCode = signObject.getString(AppConstants.CODE);
String resMsg = signObject.getString(AppConstants.MSG);
if (resCode.equals(AppConstants.SUCCESS_CODE)) {
JSONArray allEvents = signObject.getJSONArray("all");
System.out.println("INNER Response :" + allEvents);
for (int i = 0; i < allEvents.length(); i++) {
JSONObject innerObj1 = allEvents.getJSONObject(i);
String backgroundImg = innerObj1.getString("backg_img");
String declinedCount = innerObj1.getString("decli_count");
String acceptedCount = innerObj1.getString("accep_count");
String invitedCount = innerObj1.getString("invi_count");
String messages = innerObj1.getString("i_chat");
String name = innerObj1.getString("name");
String eventTime = innerObj1.getString("duration");
String userPhoto = innerObj1.getString("photo");
JSONArray viewpagerEvents = innerObj1.getJSONArray("action");
for (int u = 0; u < viewpagerEvents.length(); u++) {
JSONObject innerObj3 = viewpagerEvents.getJSONObject(u);
String buttonText = innerObj3.getString("text");
String tipsDesc = innerObj3.getString("action_text");
String buttonLink = innerObj3.getString("button_link");
final Home_Model home_data = new Home_Model(name, messages,invitedCount,declinedCount,acceptedCount,eventTime,
userPhoto,backgroundImg);
data.add(home_data);
final Home_Model_ViewPager home_viewpager = new Home_Model_ViewPager(getContext(),tipsDesc,buttonText, buttonLink);
viewPagerData.add(home_viewpager);
}
}
adapter = new HomeAdapter(getContext(),data);
pagerAdapter = new ViewPagerAdapter(getActivity(), viewPagerData);
home_recycler.setAdapter(adapter);
adapter.notifyDataSetChanged();
if (adapter.getItemCount()==0) {
noeventLayout.setVisibility(View.VISIBLE);
}
else {
noeventLayout.setVisibility(View.GONE);
}
} else if (resCode.equals(AppConstants.UPDATE_CODE)) {
//Version_Update versionUpdate=new Version_Update(SignIn.this,response);
} else {
getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
Commonfunctions.showerrorsnackbar(resMsg, getActivity(), parentLayout);
}
} catch (JSONException e) {
e.printStackTrace();
}
}//on success close
});//server callback closed
} catch (Exception e) {
e.printStackTrace();
}
}
HomeAdapter:
class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.ViewHolder> {
Context context;
List<Home_Model> students;
public HomeAdapter(Context context,List<Home_Model> students) {
this.context = context;
this.students = students;
}
#Override
public HomeAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.event_home_list, viewGroup, false);
return new HomeAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(final HomeAdapter.ViewHolder holder, final int position) {
holder.title.setText(students.get(position).getName());
holder.invited.setText(students.get(position).getInvited());
holder.accepted.setText(students.get(position).getAccept());
holder.declined.setText(students.get(position).getDecline());
holder.eventTime.setText(students.get(position).getEvent_time());
holder.messages.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getActivity(),Chat_view.class));
}
});
holder.viewPager.setAdapter(pagerAdapter);
holder.dots = new ImageView[holder.dotsCount];
for (int i = 0; i < holder.dotsCount; i++) {
holder.dots[i] = new ImageView(context);
holder.dots[i].setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_dot_gray ));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(8, 0, 8, 0);
holder.sliderDots.addView(holder.dots[i], params);
}
holder.dots[0].setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_dot_colorprimary));
holder.viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
for (int i = 0; i < holder.dotsCount; i++) {
holder.dots[i].setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_dot_gray));
}
holder.dots[position].setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_dot_colorprimary));
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
if (students.get(position).getMessages().contentEquals("false")) {
holder.status.setVisibility(View.INVISIBLE);
}
else {
holder.status.setVisibility(View.VISIBLE);
}
holder.status.setVisibility(View.INVISIBLE);
try {
Glide.with(getActivity()).load(students.get(position).getProimg()).into(holder.pro_img);
Glide.with(getActivity()).load(students.get(position).getBgimg()).into(holder.card_main);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public int getItemCount() {
return students.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView title, messages, invited, accepted, declined, eventTime;
private PorterShapeImageView pro_img;
ImageView card_main, status;
ViewPager viewPager;
LinearLayout sliderDots;
private ImageView[] dots;
private int dotsCount;
public ViewHolder(View itemView) {
super(itemView);
title = itemView.findViewById(R.id.xtv_welcome);
messages = itemView.findViewById(R.id.xtv_message);
invited = itemView.findViewById(R.id.xtv_invited);
accepted = itemView.findViewById(R.id.xtv_accepted);
declined = itemView.findViewById(R.id.xtv_decline);
eventTime = itemView.findViewById(R.id.contact_number);
pro_img = itemView.findViewById(R.id.pro_pic);
card_main = itemView.findViewById(R.id.card_main);
status = itemView.findViewById(R.id.incoming_image);
viewPager = itemView.findViewById(R.id.viewPagerTips);
sliderDots = itemView.findViewById(R.id.sliderDots);
dotsCount = pagerAdapter.getCount();
}
}
}
Please try to make one different array list for your viewpager's adapter:
ArrayList<Home_Model_ViewPager> tempList = new ArrayList<>();
for(int k=0;k<viewpagerData.size();k++){
Home_Model_ViewPager object = viewPagerData.get(k);
if(object.getTripDesc()!=null && object.getTripDesc().length() >0){
tempList.add(object);
}
}
ViewPagerAdapter pagerAdapter = new ViewPagerAdapter(getActivity(), tempList);
home_recycler.setAdapter(adapter);
adapter.notifyDataSetChanged();

How do I Set Dynamic List Follows by Dynamic Tab and Fragment in ViewPager?

How do I set dynamic list in the dynamic fragment, as I filtered data for the list using viewPager onPageSelect position but not able to set in list View due to sequence problem of fetching data?
My sequence is
TabSet>ViewPager with Fragment set>Fragmnet OnCreateView>ViewPager.onPageSelect.
But
I'm getting error of Fragment's adapter.notifyDataChange on a null object reference
Can Anyone help me out?
Here is my code:
public class MainActivity extends AppCompatActivity {
private ViewPager mViewPager;
Activity activity = getParent();
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
private ArrayList<String> catList = new ArrayList<>();
private ArrayList<String> foodItemTitle = new ArrayList<>();
private ArrayList<String> foodItemTitleList = new ArrayList<>();
LinkedHashMap<String, ArrayList<String>> titleHashMap = new LinkedHashMap<>();
LinkedHashMap<String, ArrayList<String>> fullHashMap = new LinkedHashMap<>();
LinkedHashMap<String, ArrayList<String>> halfHashMap = new LinkedHashMap<>();
LinkedHashMap<String, ArrayList<String>> qtrHashMap = new LinkedHashMap<>();
private String category;``
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getItemList();
}
private void setViewIDs() {
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.addOnPageChangeListener(viewPagerPageChangeListener);
setUpViewPager(mViewPager);
tabLayout.setupWithViewPager(mViewPager);
}
private void setUpViewPager(ViewPager viewPager) {
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
for (int i = 0; i < catList.size(); i++) {
Bundle bundle = new Bundle();
bundle.putString("data", catList.get(i));
PlaceholderFragment categoryList = new PlaceholderFragment();
categoryList.setArguments(bundle);
sectionsPagerAdapter.addFragment(categoryList, catList.get(i));
}
sectionsPagerAdapter.notifyDataSetChanged();
viewPager.setAdapter(sectionsPagerAdapter);
}
public void getItemList() {
final ProgressDialog nDialog;
nDialog = new ProgressDialog(this);
nDialog.setMessage("Loading..");
nDialog.setIndeterminate(false);
nDialog.setCancelable(true);
nDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET, MENU_ITEM_List, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("DATA");
for (int i = 0; i < jsonArray.length(); i++) {
Model model = new Model();
jsonObject = jsonArray.getJSONObject(i);
model.setItemCategory(jsonObject.getString("CAT"));
model.setItemName(jsonObject.getString("TITLE"));
//Getting Item Menu..................................
if (titleHashMap.get(model.getItemCategory()) != null) {
foodItemTitle = titleHashMap.get(model.getItemCategory());
foodItemTitle.add(model.getItemName());
titleHashMap.put(model.getItemCategory(), foodItemTitle);
} else {
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add(model.getItemName());
titleHashMap.put(model.getItemCategory(), arrayList);
}
}
category = titleHashMap.keySet().toString();
String[] cat = category.split(",");
for (int i = 0; i < cat.length; i++) {
String strReplaced = cat[i];
strReplaced = strReplaced.replace("[", "");
strReplaced = strReplaced.replace("]", "");
catList.add(strReplaced);
}
Iterator<String> key = titleHashMap.keySet().iterator();
while (key.hasNext()) {
String hashKey = key.next(); foodItemTitleList.add(titleHashMap.get(hashKey).toString());
}
setViewIDs();
nDialog.dismiss();
} catch (JSONException e) {
System.out.println("Error in code: " + e.getMessage());
nDialog.dismiss();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Time Out", Toast.LENGTH_LONG).show();
nDialog.dismiss();
}
});
RequestQueue requestqueue = Volley.newRequestQueue(this);
requestqueue.add(stringRequest);
}
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
Boolean first = true;
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if (first && positionOffset == 0 && positionOffsetPixels == 0) {
onPageSelected(0);
first = false;
}
}
#Override
public void onPageSelected(int position) {
Log.v("TabData", foodItemTitleList.get(position));
String items = foodItemTitleList.get(position);
new PlaceholderFragment().setItemDetails(items);
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment {
private ListView listView;
private ArrayList<Model> dataModelList = new ArrayList<Model>();
private ArrayAdapter<Model> adapter;
private final static String TAG = PlaceholderFragment.class.getSimpleName();
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
listView = (ListView) view.findViewById(R.id.item_list);
// setListViewAdapter();
return view;
}
private void setItemDetails(String item) {
String[] itemStr = item.split(",");
for (int i = 0; i < itemStr.length; i++) {
String oneItem = itemStr[i];
oneItem = oneItem.replace("[", "");
oneItem = oneItem.replace("]", "");
Model model = new Model();
model.setItemTitleFinal(oneItem);
Log.v("GEtdata", oneItem.toString());
dataModelList.add(model);
}
setListViewAdapter();
adapter.notifyDataSetChanged();
}
public void setListViewAdapter() {
dataModelList = new ArrayList<Model>();
adapter = new MenuListAdapter(getActivity(), R.layout.food_item_list, dataModelList);
listView.setAdapter(adapter);
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// Log.v("TabData", foodItemTitleList.get(position));
return mFragmentList.get(position);
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public int getCount() {
return mFragmentList.size();
}
#Override
public CharSequence getPageTitle(int position) {
Toast.makeText(getApplicationContext(), "CharSequence", Toast.LENGTH_SHORT).show();
switch (position) {
}
return mFragmentTitleList.get(position);
}
}
}
This is my adapter:
public class MenuListAdapter extends ArrayAdapter<Model> {
private Activity activity;
LinkedHashMap<String, ArrayList<String>> fullHashMap = new LinkedHashMap<>();
LinkedHashMap<String, ArrayList<String>> halfHashMap = new LinkedHashMap<>();
LinkedHashMap<String, ArrayList<String>> qtrHashMap = new LinkedHashMap<>();
ArrayList<String> foodItemTitle = new ArrayList<>();
private ArrayList<String> priceFull = new ArrayList<>();
private ArrayList<String> priceHalf = new ArrayList<>();
private ArrayList<String> priceQtr = new ArrayList<>();
private String full;
private String half;
private String qtr;
public MenuListAdapter(Activity activity, int resource, List<Model> dataModelList) {
super(activity, resource, dataModelList);
this.activity = activity;
// getItemList();
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
//If holder not exist then loacte all view from UI file.
if (convertView == null) {
convertView = inflater.inflate(R.layout.food_item_list, parent, false);
holder = new ViewHolder(convertView);
final ImageButton removeBtn = convertView.findViewById(R.id.img_remove);
final ImageButton addBtn = convertView.findViewById(R.id.img_add);
final TextView spinnerItemQuanty = convertView.findViewById(R.id.spinner_item_quantity);
final TextView totalPrice = convertView.findViewById(R.id.total_price);
final TextView item = convertView.findViewById(R.id.item_name);
final ViewHolder finalHolder = holder;
removeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String currentQnty = spinnerItemQuanty.getText().toString().trim();
int qnty = Integer.valueOf(currentQnty);
qnty = qnty - 1;
if (qnty >= 0)
spinnerItemQuanty.setText(String.valueOf(qnty));
}
});
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String currentQnty = spinnerItemQuanty.getText().toString().trim();
int qnty = Integer.valueOf(currentQnty);
spinnerItemQuanty.setText(String.valueOf(qnty + 1));
String title = item.getText().toString();
customPopUp(title);
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Model model = getItem(position);
holder.itemTitle.setText(model.getItemTitleFinal());
return convertView;
}
private void customPopUp(String title) {
final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getContext());
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View dialogView = inflater.inflate(R.layout.price_popup, null);
dialogBuilder.setView(dialogView);
TextView itemName = dialogView.findViewById(R.id.popTitle);
Button cancel = dialogView.findViewById(R.id.cancel_order);
Button select = dialogView.findViewById(R.id.add_order);
itemName.setText(title);
final AlertDialog alert = dialogBuilder.create();
alert.show();
}
public void getItemList() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, MENU_ITEM_List, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("DATA");
for (int i = 0; i < jsonArray.length(); i++) {
Model model = new Model();
jsonObject = jsonArray.getJSONObject(i);
model.setItemName(jsonObject.getString("TITLE"));
}
// nDialog.dismiss();
} catch (JSONException e) {
System.out.println("Error in code: " + e.getMessage());
// nDialog.dismiss();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(), "Time Out", Toast.LENGTH_LONG).show();
// nDialog.dismiss();
}
});
RequestQueue requestqueue = Volley.newRequestQueue(getContext());
requestqueue.add(stringRequest);
}
}
private static class ViewHolder {
private TextView itemTitle;
private Spinner spinnerItem;
private ImageButton removeBtn;
private ImageButton addBtn;
private TextView spinnerItemQuanty;
private TextView totalPrice;
public ViewHolder(View v) {
itemTitle = v.findViewById(R.id.item_name);
spinnerItemQuanty = v.findViewById(R.id.spinner_item_quantity);
totalPrice = v.findViewById(R.id.total_price);
}
}
}
Here is list of title filtered according to category:
Category: [MORNING SPECIAL, DESSERT & ICE CREAM, CHINESE]
Food ITEMS: [[Tea, Puri Sabji, Samosa, momos], [ROSOGULLA, Softy], [Chicken Tandoori, Chicken Korma]]
I am trying to add food items to list but array adapter getting null data because onCreateView set first then I am getting data from onPageSelect that's why my application get crashed down.

Looping through ViewPager Images Android

I am developing an android app where I use viewpager to show some images from a rest api. These Api has lots of images in json format. I only want to show the the first 8 or 10 images into viewpager. But I am not getting the correct way to loop throug the images. Here is my code for view pager.
private static ViewPager viewPager;
private static int currentPage = 0;
private List<NewsModel> imageList=new ArrayList<>( );
private ViewPagerAdapter adapter;
private NewsController mController;
private Timer swipeTimer;
private Handler handler;
private Runnable Update;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.option_main_fragment, container, false);
viewPager = view.findViewById(R.id.pager);
adapter=new ViewPagerAdapter( this.getActivity(),imageList );
CircleIndicator indicator = (CircleIndicator) view.findViewById(R.id.indicator);
viewPager.setAdapter(adapter);
indicator.setViewPager(viewPager);
adapter.registerDataSetObserver(indicator.getDataSetObserver());
mController = new NewsController(this);
mController.startFetching();
return view;
}
#Override
public void onResume() {
// Auto start of viewpager
handler = new Handler();
Update= new Runnable() {
public void run() {
if (currentPage == imageList.size()) {
currentPage = 0;
}
viewPager.setCurrentItem(currentPage++, true);
System.out.println(viewPager.getCurrentItem());
}
};
swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(Update);
}
},2000,5000);
super.onResume();
}
#Override
public void onPause() {
swipeTimer.cancel();
super.onPause();
}
Edited Code This is the code for fetching json data
public class NewsController {
private static final String TAG = NewsController.class.getSimpleName();
private UserCallbackListener mListener;
private NewsRestApiManager mApiManager;
private AppImage appImages;
Realm news_realm;
ArrayList<String> title_list = new ArrayList<>();
GlobalClass globalClass = new GlobalClass();
public NewsController(UserCallbackListener listener) {
mListener = listener;
mApiManager = new NewsRestApiManager();
}
public void startFetching(){
news_realm = Realm.getDefaultInstance();
mApiManager.getNewsApi().getNews(new Callback<String>() {
#Override
public void success(String s, Response response) {
Log.d(TAG, "JSON :: " + s);
try {
JSONArray array = new JSONArray(s);
for(int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
NewsModel news = new NewsModel();
news.setTitle( jsonObject.optString( "title") );
news.setBody( jsonObject.optString( "body" ) );
news.setUpdatedAt( jsonObject.getString( "updated_at" ) );
ArrayList<AppImage> list = new ArrayList();
JSONArray imageArray =jsonObject.getJSONArray("appImages");
if (imageArray.length() > 1) {
for(int j=0; j<imageArray.length();j++){
appImages = new AppImage();
try {
appImages.setSrc( new JSONArray( s ).getJSONObject( i ).getJSONArray( "appImages" ).getJSONObject( j ).optString( "src" ) );
}catch (JSONException e){
e.printStackTrace();
}
list.add(appImages);
}
}
news.setAppImages( list );
TeaserImageSmall coverImage=new TeaserImageSmall();
try {
coverImage.setSrc( jsonObject.getJSONObject("teaserImageSmall").optString("src"));
news.setTeaserImageSmall(coverImage);
} catch (JSONException e) {
Log.d(TAG, "News image could not be loaded for: " + news.getTitle());
}
mListener.onFetchProgressNews(news);
}
} catch (JSONException e) {
mListener.onFetchFailed();
}
mListener.onFetchComplete();
}
#Override
public void failure(RetrofitError error) {
Log.d(TAG, "Error :: " + error.getMessage());
mListener.onFetchComplete();
}
});
}
public interface UserCallbackListener{
void onFetchProgressNews(NewsModel news);
void onFetchComplete();
void onFetchFailed();
}
}
Adapter Class
public class ViewPagerAdapter extends PagerAdapter{
private List<NewsModel> imageList;
private LayoutInflater layoutInflater;
private Context context;
public ViewPagerAdapter(Context context, List<NewsModel> imageList) {
this.context = context;
this.imageList=imageList;
}
#Override
public int getCount() {
return imageList.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view==object;
}
#Override
public Object instantiateItem(ViewGroup view, int position) {
layoutInflater=(LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
View itemView = layoutInflater.inflate(R.layout.sliding_img_layout, view, false);
final NewsModel imageFromNews=imageList.get( position );
ImageView myImage = itemView.findViewById(R.id.sliding_image);
Picasso.with(itemView.getContext()).load(imageFromNews.getTeaserImageSmall().getSrc()).into( myImage );
view.addView(itemView, 0);
myImage.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i=new Intent(context,DetailNews.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("src",imageFromNews.getTeaserImageSmall().getSrc());
i.putExtra("title",imageFromNews.getTitle());
i.putExtra("body",imageFromNews.getBody());
context.startActivity(i);
}
} );
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
I guess you can change the code as below
ArrayList<AppImage> list = new ArrayList();
JSONArray imageArray =jsonObject.getJSONArray("appImages");
if (imageArray.length() > 1) {
for(int j=0; j<imageArray.length() && j < 8;j++) { // Added condition j < 8
appImages = new AppImage();
try {
appImages.setSrc( new JSONArray( s ).getJSONObject( i ).getJSONArray( "appImages" ).getJSONObject( j ).optString( "src" ) );
}catch (JSONException e){
e.printStackTrace();
}
list.add(appImages);
}
}
news.setAppImages( list );
there are other ways to do this as well
you can fix viewpager item count
#Override
public int getCount() {
return imageList.size() <= 8? imageList.size():8;
}

Remove JSON Object from JSON Array on onClick in Android

I have a RecyclerView and when a user clicks on an item, that item gets selected and its id is saved in a JSON Array. Similarly, if the user selects an item and later decides to unselect it, the item should be removed from the JSON Array and an updated array should be created. I am able to create a JSON Array on onClick but at !onClick I am not able to remove the JSON Object from the JSON Array.
Here is my Adapter Class:
public class ClientListAdapter extends RecyclerView.Adapter<ClientListAdapter.ViewHolder> {
private Context context;
private List<ClientListData> clientListData;
public JSONArray clientArray = new JSONArray();
public ClientListAdapter(List<ClientListData> clientListData, Context context) {
super();
this.clientListData = clientListData;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.client_list_item, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(final ClientListAdapter.ViewHolder holder, final int position) {
final ClientListData clientListDataModel = clientListData.get(position);
holder.clientList.setText(clientListDataModel.getClientName());
holder.itemView.setBackgroundColor(clientListDataModel.isSelected() ? Color.GRAY : Color.WHITE);
holder.clientList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clientListDataModel.setSelected(!clientListDataModel.isSelected());
try {
JSONObject clientObject = new JSONObject();
if(clientListDataModel.isSelected()) {
holder.itemView.setBackgroundColor(Color.GRAY);
clientObject.put("id", clientListData.get(position).getClientId());
clientArray.put(clientObject);
}
if(!clientListDataModel.isSelected()) {
holder.itemView.setBackgroundColor(Color.WHITE);
for(int i=0; i<clientArray.length(); i++) {
clientObject = clientArray.getJSONObject(i);
clientObject.remove(clientListData.get(position).getClientId());
//clientArray.put(clientObject);
}
}
//clientArray.put(clientObject);
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("client id array", ""+clientArray);
}
});
}
#Override
public int getItemCount() {
return clientListData == null ? 0:clientListData.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public TextView clientList;
public ViewHolder(View itemView) {
super(itemView);
clientList = (TextView) itemView.findViewById(R.id.tv_client_list);
}
}
}
and here is my Model Class:
public class ClientListData {
private String clientId;
private String clientName;
private boolean isSelected = false;
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String getClientName() {
return clientName;
}
public void setClientName(String clientName) {
this.clientName = clientName;
}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean selected) {
isSelected = selected;
}
}
Note that I have created a boolean variable in the Model Class to listen to onClicks.
Note:- since I am using org.json, I am not able to use the remove method on JSON Array, after a lot of search I came across this question.
Try this:[UPDATE]
if (!clientListDataModel.isSelected()) {
holder.itemView.setBackgroundColor(Color.WHITE);
for (int i = 0; i < clientArray.length(); i++) {
clientObject = clientArray.getJSONObject(i);
if (clientObject.getString("id").equals(clientListDataModel.getClientId())) {
clientArray=removeFromJsonArray(clientArray,i);
break;
}
}
}
removeFromJsonArray function:
private JSONArray removeFromJsonArray(JSONArray array,int position){
if(array==null)return null;
JSONArray newArray = new JSONArray();
for (int i=0;i<array.length();i++)
{
//Excluding the item at position
if (i != position)
{
newArray.put(jsonArray.get(i));
}
}
return newArray;
}
Add This code in activity
private ArrayList<Integer> selectedIdList = new ArrayList<>();
ClientListAdapter adapter=new ClientListAdapter (list,this,new View.OnClickListener() {
#Override
public void onClick(View v) {
int position=(Integer)v.getTag();
if(list.size()>position){
ClientListDataModel clientListDataModel=list.get(position);
if clientListDataModel!= null) {
clientListDataModel.setSelected(!clientListDataModel.isSelected());
boolean isSelected = clientListDataModel.isSelected();
if (!isSelected) {
if (selectedIdList.contains(clientListDataModel.getId())) {
int index = selectedIdList.indexOf(clientListDataModel.getId());
selectedIdList.remove(index);
}
} else {
if (!selectedIdList.contains(clientListDataModel.getId())) {
selectedIdList.add(clientListDataModel.getId());
}
}
}
adapter.notifyItemChanged(pos);
}
});
And at sending time
public JSONArray clientArray = new JSONArray();
if(!selectedIdList.empty()){
for(int i=0; i<selectedIdList.size(); i++) {
JSONObject clientObject = new JSONObject();
clientObject.put("id", selectedIdList.get(i));
clientArray.put(clientObject);
}
}
public class ClientListAdapter extends RecyclerView.Adapter<ClientListAdapter.ViewHolder> {
private Context context;
private List<ClientListData> clientListData;
public JSONArray clientArray = new JSONArray();
OnClickListener onClickListener;
public ClientListAdapter(List<ClientListData> clientListData, Context context,OnClickListener onclick) {
super();
this.clientListData = clientListData;
this.context = context;
onClickListener=onclick;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.client_list_item, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(final ClientListAdapter.ViewHolder holder, final int position) {
final ClientListData clientListDataModel = clientListData.get(position);
holder.clientList.setText(clientListDataModel.getClientName());
holder.itemView.setBackgroundColor(clientListDataModel.isSelected() ? Color.GRAY : Color.WHITE);
holder.clientList.setTag(position);
holder.clientList.setOnClickListener(onClickListener);
}
#Override
public int getItemCount() {
return clientListData == null ? 0:clientListData.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public TextView clientList;
public ViewHolder(View itemView) {
super(itemView);
clientList = (TextView) itemView.findViewById(R.id.tv_client_list);
}
}

Un-filtering the result is not working in Recyclerview

I have a recyclerview with some data and I have a searchview, and filter is working just fine. But un-filtering not working. I can't get the whole data in the recyclerview after un-filter. No data is showing. I have to re-open the activity to get data. I tried to used two data sets. But i have no idea where to use them.
My Fragment.
public class YourDealerListFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private static final String STATE_DEALER_LIST = "state_dealer_list";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private VollySingleton vollySingleton;
private RequestQueue requestQueue;
private RecyclerView recyclerView;
private DealerListAdapter dlAdapter;
private HashMap<String, String> hashMap;
private ArrayList<SuggestGetSet> dealerList = new ArrayList<>();
private ArrayList<SuggestGetSet> filteredDealerList = new ArrayList<>();
private String repNo;
private StaggeredGridLayoutManager staggeredGridLayoutManager;
private GridMenuFragment mGridMenuFragment;
private Toolbar toolbar;
private ItemSorter itemSorter;
private Button sortButton;
private SearchView searchView;
private ProgressView progressView;
public static List<String> disChannel;
public YourDealerListFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment YourDealerListFragment.
*/
// TODO: Rename and change types and number of parameters
public static YourDealerListFragment newInstance(String param1, String param2) {
YourDealerListFragment fragment = new YourDealerListFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
vollySingleton = VollySingleton.getsInstance();
requestQueue = vollySingleton.getmRequestQueue();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_your_dealer_list, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.dealerListRecyclerView);
progressView = (ProgressView) view.findViewById(R.id.pViewew);
itemSorter = new ItemSorter();
dlAdapter = new DealerListAdapter();
disChannel = new ArrayList<String>();
repNo = UserLogIn.getRepNo();
if (savedInstanceState != null) {
dealerList = savedInstanceState.getParcelableArrayList(STATE_DEALER_LIST);
dlAdapter.setDealertList(dealerList);
} else {
getJsonRequest();
}
final FrameLayout frameLayout = (FrameLayout) view.findViewById(R.id.frame_layout);
frameLayout.getBackground().setAlpha(0);
final FloatingActionsMenu fabMenu = (FloatingActionsMenu) view.findViewById(R.id.fab_menu);
final FloatingActionButton fabName = (FloatingActionButton) view.findViewById(R.id.fab_name);
final FloatingActionButton fabCollection = (FloatingActionButton) view.findViewById(R.id.fab_collection);
fabName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onSortByName();
fabMenu.collapse();
}
});
fabMenu.setOnFloatingActionsMenuUpdateListener(new FloatingActionsMenu.OnFloatingActionsMenuUpdateListener() {
#Override
public void onMenuExpanded() {
frameLayout.getBackground().setAlpha(240);
frameLayout.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
fabMenu.collapse();
return true;
}
});
}
#Override
public void onMenuCollapsed() {
frameLayout.getBackground().setAlpha(0);
frameLayout.setOnTouchListener(null);
}
});
searchView = (SearchView) view.findViewById(R.id.dealerNameSearchView);
searchView.setOnQueryTextListener(listener);
//custom context menu
mGridMenuFragment = GridMenuFragment.newInstance(R.drawable.background);
setupGridMenu();
mGridMenuFragment.setOnClickMenuListener(new GridMenuFragment.OnClickMenuListener() {
#Override
public void onClickMenu(GridMenu gridMenu, int position) {
switch (position) {
case 0:
Intent intent = new Intent(getActivity(), SelectItem.class);
getActivity().finish();
startActivity(intent);
getActivity();
break;
}
}
});
//dealers' recycler view item click
recyclerView.addOnItemTouchListener(new NavigationDrawerFragment.RecycleTouchListner(getActivity(), recyclerView, new NavigationDrawerFragment.ClickListener() {
#Override
public void onClick(View view, int position) {
FragmentTransaction tx = getActivity().getSupportFragmentManager().beginTransaction();
tx.replace(R.id.main_frame, mGridMenuFragment);
tx.addToBackStack(null);
tx.commit();
}
}));
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setHasOptionsMenu(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
staggeredGridLayoutManager = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(staggeredGridLayoutManager);
final ArrayList<SuggestGetSet> filteredModelList = new ArrayList<>();
for (SuggestGetSet movie : filteredModelList) {
filteredModelList.add(movie);
}
dlAdapter = new DealerListAdapter(filteredModelList, getActivity());
recyclerView.setAdapter(dlAdapter);
}
//search dealer from search view
SearchView.OnQueryTextListener listener = new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
final ArrayList<SuggestGetSet> filteredModelList = filter(dealerList, s);
dlAdapter.animateTo(filteredModelList);
recyclerView.scrollToPosition(0);
return true;
}
};
private ArrayList<SuggestGetSet> filter(ArrayList<SuggestGetSet> models, String query) {
query = query.toLowerCase();
final ArrayList<SuggestGetSet> filteredModelList = new ArrayList<>();
for (SuggestGetSet model : models) {
final String text = model.getName().toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}
//custom context menu data
private void setupGridMenu() {
List<GridMenu> menus = new ArrayList<>();
menus.add(new GridMenu("Order", R.drawable.nnn));
menus.add(new GridMenu("Banking", R.drawable.n));
menus.add(new GridMenu("Credit Note", R.drawable.nn));
menus.add(new GridMenu("Cheques", R.drawable.nnnn));
menus.add(new GridMenu("Invoice Dispatch", R.drawable.nnnnn));
menus.add(new GridMenu("Goods Return", R.drawable.nnnnnn));
mGridMenuFragment.setupMenu(menus);
}
private void getJsonRequest() {
progressView.start();
final SQLiteHandler sqLiteHandler = new SQLiteHandler(getActivity().getApplicationContext());
Cursor cr = sqLiteHandler.getData(sqLiteHandler);
cr.moveToFirst();
do {
repNo = cr.getString(0);
} while (cr.moveToNext());
cr.close();
CustomJsonObjectRequest request = new CustomJsonObjectRequest(Request.Method.POST, AppConfig.URL_JSON_DEALER_LIST, hashMap, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
progressView.stop();
try {
JSONObject jsonObject = new JSONObject(String.valueOf(response));
if (jsonObject.names().get(0).equals("feed")) {
dealerList = parseJsonResponse(response);
dlAdapter.setDealertList(dealerList);
JSONArray arrayAchSum = response.getJSONArray("feedd");
for (int i = 0; i < arrayAchSum.length(); i++) {
JSONObject obj3 = arrayAchSum.getJSONObject(i);
String a = obj3.getString("dis_channel");
disChannel.add(a);
}
} else {
Toast.makeText(getActivity(), "No Dealers Available", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
/*dealerList = parseJsonResponse(response);
dlAdapter.setDealertList(dealerList);*/
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
protected Map<String, String> getParams() throws AuthFailureError {
hashMap = new HashMap<String, String>();
hashMap.put("repNo", repNo);
return hashMap;
}
};
requestQueue.add(request);
request.setRetryPolicy(new DefaultRetryPolicy(15 * 1000, 0,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}
private ArrayList<SuggestGetSet> parseJsonResponse(JSONObject response) {
ArrayList<SuggestGetSet> groupList = new ArrayList<>();
if (response != null || response.length() > 0) {
try {
JSONArray arrayDelaers = response.getJSONArray(KEY_FEED_NAME);
for (int i = 0; i < arrayDelaers.length(); i++) {
JSONObject currentObject = arrayDelaers.getJSONObject(i);
String rep = currentObject.getString(KEY_REP_ID);
String name = currentObject.getString(KEY_REP_NAME);
String dealerId = currentObject.getString(KEY_DEALER_ID);
SuggestGetSet delaers = new SuggestGetSet();
delaers.setId(rep);
delaers.setName(name);
delaers.setDealerId(dealerId);
groupList.add(delaers);
}
//Toast.makeText(getApplicationContext(), productList.toString(), Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
return groupList;
}
public void onSortByName() {
itemSorter.sortItemByName(dealerList);
dlAdapter.notifyDataSetChanged();
}
public static interface ClickListener {
public void onClick(View view, int position);
//public void onLongClick(View view, int position);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(STATE_DEALER_LIST, dealerList);
}
}
My Adapter class.
public class DealerListAdapter extends RecyclerView.Adapter<DealerListAdapter.ViewHolderDealerList> {
private LayoutInflater layoutInflater;
public Context mcontext;
private List<SuggestGetSet> dealerArrayList;
private List<SuggestGetSet> originalDealerArrayList;
Typeface type;
private static String selectedRepId, selectedDealerId, selectedDealerName;
public DealerListAdapter() {
}
public DealerListAdapter(Context context) {
layoutInflater = LayoutInflater.from(context);
type = Typeface.createFromAsset(context.getAssets(), "helvr.ttf");
}
public static String getDealerName() {
return selectedDealerName;
}
public static String getDealerID() {
return selectedDealerId;
}
public static String getRepID() {
return selectedRepId;
}
public DealerListAdapter(ArrayList<SuggestGetSet> dList, Context context) {
this.mcontext = context;
layoutInflater = LayoutInflater.from(context);
dealerArrayList = new ArrayList<>(dList);
originalDealerArrayList = new ArrayList<>(dList);
type = Typeface.createFromAsset(context.getAssets(), "helvr.ttf");
}
public void setDealertList(ArrayList<SuggestGetSet> dealerAList) {
this.dealerArrayList = dealerAList;
originalDealerArrayList = new ArrayList<>(dealerAList);
notifyItemRangeChanged(0, dealerArrayList.size());
}
#Override
public ViewHolderDealerList onCreateViewHolder(ViewGroup parent, int viewType) {
View view = layoutInflater.inflate(R.layout.custom_dealer_list_layout, parent, false);
ViewHolderDealerList viewHolderDealerList = new ViewHolderDealerList(view);
return viewHolderDealerList;
}
#Override
public void onBindViewHolder(ViewHolderDealerList holder, int position) {
final SuggestGetSet model = dealerArrayList.get(position);
holder.bind(model);
final int pos = position;
holder.dealerName.setText(dealerArrayList.get(position).getName());
holder.dealerName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectedDealerId = dealerArrayList.get(pos).getDealerId();
selectedRepId = dealerArrayList.get(pos).getId();
selectedDealerName = dealerArrayList.get(pos).getName();
Toast.makeText(layoutInflater.getContext(), dealerArrayList.get(pos).getName() + " / " + dealerArrayList.get(pos).getDealerId() + " / " + dealerArrayList.get(pos).getId(), Toast.LENGTH_LONG).show();
}
});
}
#Override
public int getItemCount() {
return dealerArrayList.size();
}
public void setModels(ArrayList<SuggestGetSet> models) {
dealerArrayList = new ArrayList<>(models);
}
static class ViewHolderDealerList extends RecyclerView.ViewHolder {
private TextView dealerName, dealerId;
public ViewHolderDealerList(View itemView) {
super(itemView);
dealerName = (TextView) itemView.findViewById(R.id.yourDelaerName);
//dealerId = (TextView) itemView.findViewById(R.id.txtDelaerCollection);
}
public void bind(SuggestGetSet model) {
dealerName.setText(model.getName());
}
}
//search animations
public SuggestGetSet removeItem(int position) {
final SuggestGetSet model = dealerArrayList.remove(position);
notifyItemRemoved(position);
return model;
}
public void addItem(int position, SuggestGetSet model) {
dealerArrayList.add(position, model);
notifyItemInserted(position);
}
public void moveItem(int fromPosition, int toPosition) {
final SuggestGetSet model = dealerArrayList.remove(fromPosition);
dealerArrayList.add(toPosition, model);
notifyItemMoved(fromPosition, toPosition);
}
public void animateTo(ArrayList<SuggestGetSet> models) {
applyAndAnimateRemovals(models);
applyAndAnimateAdditions(models);
applyAndAnimateMovedItems(models);
}
private void applyAndAnimateMovedItems(ArrayList<SuggestGetSet> models) {
for (int toPosition = dealerArrayList.size() - 1; toPosition >= 0; toPosition--) {
final SuggestGetSet model = dealerArrayList.get(toPosition);
final int fromPosition = models.indexOf(model);
if (fromPosition >= 0 && fromPosition != toPosition) {
moveItem(fromPosition, toPosition);
}
}
notifyDataSetChanged();
}
private void applyAndAnimateAdditions(ArrayList<SuggestGetSet> models) {
for (int i = 0, count = dealerArrayList.size(); i < count; i++) {
final SuggestGetSet model = dealerArrayList.get(i);
if (!models.contains(model)) {
addItem(i, model);
}
}
notifyDataSetChanged();
}
private void applyAndAnimateRemovals(ArrayList<SuggestGetSet> models) {
for (int i = dealerArrayList.size() - 1; i >= 0; i--) {
final SuggestGetSet model = dealerArrayList.get(i);
if (!models.contains(model)) {
removeItem(i);
}
}
notifyDataSetChanged();
}
}
Just Modify your function and Add check for null or "" .
it will work fine
private ArrayList<SuggestGetSet> filter(ArrayList<SuggestGetSet> models, String query) {
if(TextUtils.isEmpty(query)){
return models;
}
query = query.toLowerCase();
final ArrayList<SuggestGetSet> filteredModelList = new ArrayList<>();
for (SuggestGetSet model : models) {
final String text = model.getName().toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}

Categories

Resources