checkbox select and deselect - java

package com.example.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;
import com.example.aayushchaubey.meetdax.R;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.HashMap;
public class DifferentGenderServicesAdapter2 extends RecyclerView.Adapter {
private Task<QuerySnapshot> task;
String id, servicename;
ArrayList<String> serviceArray = new ArrayList<>();
ArrayList<Integer> costArray = new ArrayList<>();
ArrayList<ArrayList<String>> stylistIdArray = new ArrayList<>();
ArrayList<Integer>durationArray=new ArrayList<>();
TextView serviceTv, durationTv;
int count = 0;
String strService;
ArrayList<String> keyArr = new ArrayList<>();
ArrayList<String>serviceDocumentId=new ArrayList<>();
ArrayList<String>selectedServiceId=new ArrayList<>();
ArrayList<String>selectedServiceArray=new ArrayList<>();
ArrayList<Integer>selectedServiceCost=new ArrayList<>();
ArrayList<Integer>durationArr=new ArrayList<>();
String serviceId,strStylist,strDuration;
ArrayList<String>stylist=new ArrayList<>();
ArrayList<ArrayList<String>>selectedStylistId=new ArrayList<>();
public DifferentGenderServicesAdapter2(Task<QuerySnapshot> task, ArrayList<String> id, TextView servicesTv, TextView durationTv) {
this.task = task;
this.serviceTv = servicesTv;
this.durationTv = durationTv;
this.serviceDocumentId=id;
count = task.getResult().size();
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.services_item, parent, false);
return new DifferentGenderServicesAdapter2.listViewHolder(view);
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
try {
((listViewHolder) holder).servicenameTv.setText(task.getResult().getDocuments().get(position).get("name").toString());
((listViewHolder) holder).serviceCost.setText(task.getResult().getDocuments().get(position).get("price").toString());
servicename = task.getResult().getDocuments().get(position).get("name").toString();
Integer price = task.getResult().getDocuments().get(position).getLong("price").intValue();
serviceArray.add(servicename);
costArray.add(price);
ArrayList<HashMap<String,String>>stylistArr=new ArrayList<>();
stylistArr=(ArrayList<HashMap<String, String>>)task.getResult().getDocuments().get(position).get("services");
ArrayList<String> stylistsId = new ArrayList<String>();
stylistsId.clear();
for (int i=0;i<stylistArr.size();i++){
strStylist=stylistArr.get(i).get("stylist").toString();
strDuration=stylistArr.get(i).get("duration").toString();
stylistsId.add(strStylist);
durationArray.add(Integer.parseInt(strDuration));
}
stylistIdArray.add(stylistsId);
((listViewHolder) holder).checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(((listViewHolder) holder).checkBox.isChecked()){
String service=serviceArray.get(position);
selectedServiceArray.add(service);
serviceTv.setText(selectedServiceArray.toString().replaceAll("\\[|\\]", ""));
}else {
selectedServiceArray.remove(position);
if (selectedServiceArray.size()== 0) {
serviceTv.setText("0");
} else {
serviceTv.setText(selectedServiceArray.toString());
}
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
public ArrayList<String> getServiceId() {
return selectedServiceId;
}
public ArrayList<String> getServices() {
return selectedServiceArray;
}
public Integer getCostArray() {
Integer cost = null;
if(selectedServiceCost.size()>1){
cost=selectedServiceCost.get(0)+selectedServiceCost.get(1);
}else {
cost=selectedServiceCost.get(0);
}
return cost;
}
public Integer getDurationArr() {
Integer duration=null;
if(durationArr.size()>1){
duration=durationArr.get(0)+durationArr.get(1);
}else {
duration=durationArr.get(0);
}
return duration;
}
public ArrayList<ArrayList<String>> getSelectedStylistId() {
return selectedStylistId;
}
#Override
public int getItemCount() {
return count;
}
private class listViewHolder extends RecyclerView.ViewHolder {
private CheckBox checkBox;
private TextView servicenameTv, serviceCost;
int count = 0;
String strService;
public listViewHolder(final View itemView) {
super(itemView);
try {
servicenameTv = (TextView) itemView.findViewById(R.id.damerServiceTV);
serviceCost = (TextView) itemView.findViewById(R.id.damerRsTV);
checkBox = (CheckBox) itemView.findViewById(R.id.checkBox);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
This is the recycleradapter i am using to populate array and checkbox.i want to setText for selected items.If i deselect the items i want to remove text from textview.When i select one item select and deselect is working properly.If i had more than one or if i select and deselct multiples times its not working giving index error

You are trying to delete an item at the given ReciclerView selection, but this position is wrong because you are doing:
selectedServiceArray.add(service);
So you don't know the position which is added because could be other items in this array. You have to request delete the object instead the position. Try this:
if(checkbox.isChecked){
String service=serviceArray.get(getAdapterPosition);
selectedServiceArray.add(service);
holder.serviceNameTv.setText(selectedServiceArray.toString);
} else {
String service=serviceArray.get(getAdapterPosition);
selectedServiceArray.remove(service);
holder.serviceNameTv.setText(selectedServiceArray.toString);
}

Do it like this : -
if(checkbox.isChecked){
String service=serviceArray.get(getAdapterPosition)
selectedServiceArray.add(service);
holder.serviceNameTv.setText(selectedServiceArray.toString);
}
else{
selectedServiceArray.remove(getAdapterPosition);
if (selectedServiceArray.size = 0) {
holder.serviceNameTv.setText("0");
} else{
holder.serviceNameTv.setText(selectedServiceArray.toString);
}

Related

How can I reduce the time for retrieving data from postgresql?

The code is working but it is taking 14-16 seconds to retrieve data of just 1 video from postgresql server. I think there might be a proper way of retrieving the data. Please help me with this.
Thank you.
FreeClassesAdapter.java
import android.app.Activity;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.android.volley.RequestQueue;
import com.athrved.masterclass.PlayerActivity;
import com.athrved.masterclass.R;
import com.squareup.picasso.Picasso;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
public class FreeclassesAdapter extends RecyclerView.Adapter<FreeclassesAdapter.FreeViewHolder> {
ArrayList<FreeHelperClass> featloc;
public static String a,b="FAILED TO LOAD";
public static String videoId1;
RequestQueue requestQueue;
private static String V_id1;
public FreeclassesAdapter(ArrayList<FreeHelperClass> featloc) {
this.featloc = featloc;
}
#NonNull
#Override
public FreeViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.free_class_card_design,parent,false);
FreeViewHolder freeViewHolder = new FreeViewHolder(view);
return freeViewHolder;
}
#Override
public void onBindViewHolder(#NonNull FreeViewHolder holder, int position) {
FreeHelperClass freeHelperClass = featloc.get(position);
holder.imagesmall1.setImageResource(freeHelperClass.getImagesmall1());
holder.imagesmall2.setImageResource(freeHelperClass.getImagesmall2());
holder.title.setText(freeHelperClass.getTitle());
holder.topic.setText(freeHelperClass.getTopic());
holder.author.setText(freeHelperClass.getAuthor());
Database db=new Database();
videoId1=V_id1;
if(position==0){
Picasso.get().load("https://img.youtube.com/vi/"+videoId1+"/maxresdefault.jpg").into(holder.imagebig);
}
if(position==1){
Picasso.get().load("https://img.youtube.com/vi/lrcqt4RelJ4/maxresdefault.jpg").into(holder.imagebig);
}
}
#Override
public int getItemCount() {
return featloc.size();
}
public static class FreeViewHolder extends RecyclerView.ViewHolder{
ImageView imagebig, imagesmall1,imagesmall2;
TextView topic, author;
TextView title;
Button bookmark, bookmark_border;
public FreeViewHolder(#NonNull final View itemView){
super(itemView);
imagebig=itemView.findViewById(R.id.freeimgbig);
imagesmall1=itemView.findViewById(R.id.freec1_image);
imagesmall2=itemView.findViewById(R.id.freec2_image);
bookmark=itemView.findViewById(R.id.bookmarkfree);
bookmark_border=itemView.findViewById(R.id.bookmarkfree_border);
title=itemView.findViewById(R.id.freec_title);
topic=itemView.findViewById(R.id.freec_topic);
author=itemView.findViewById(R.id.freec_author);
bookmark_border.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(getAdapterPosition()==0){
bookmark_border.setVisibility(View.GONE);
bookmark.setVisibility(View.VISIBLE);
}
if(getAdapterPosition()==1){
bookmark_border.setVisibility(View.GONE);
bookmark.setVisibility(View.VISIBLE);
}
}
});
bookmark.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(getAdapterPosition()==0){
bookmark_border.setVisibility(View.VISIBLE);
bookmark.setVisibility(View.GONE);
}
if(getAdapterPosition()==1){
bookmark_border.setVisibility(View.VISIBLE);
bookmark.setVisibility(View.GONE);
}
}
});
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
videoId1=V_id1;
if (getAdapterPosition() == 0) {
Intent intent = new Intent(itemView.getContext(), PlayerActivity.class);
intent.putExtra("VIDEOID", videoId1);
itemView.getContext().startActivity(intent);
Activity activity = (Activity) itemView.getContext();
activity.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
if (getAdapterPosition() == 1) {
Intent intent = new Intent(itemView.getContext(), PlayerActivity.class);
intent.putExtra("VIDEOID", "lrcqt4RelJ4");
itemView.getContext().startActivity(intent);
Activity activity = (Activity) itemView.getContext();
activity.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
}
});
}
}
private class Database {
private Connection connection;
private final String host = "ec2-54-158-232-223.compute-1.amazonaws.com";
private final String database = "ddgaguv61p4m63";
private final int port = 5432;
private final String user = "jfeitasqnyuanh";
private final String pass = "d60b43b4e9ea924c91deb754cf18a51d5948b7a7e58b4e4d0045487767174ad8";
private String url = "jdbc:postgresql://ec2-54-158-232-223.compute-1.amazonaws.com:5432/ddgaguv61p4m63?sslmode=require&user=jfeitasqnyuanh&password=d60b43b4e9ea924c91deb754cf18a51d5948b7a7e58b4e4d0045487767174ad8";
private boolean status;
public Database() {
this.url = String.format(this.url, this.host, this.port, this.database);
connect();
//this.disconnect();
System.out.println("connection status:" + status);
}
private void connect() {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
Class.forName("org.postgresql.Driver");
connection = DriverManager.getConnection(url, user, pass);
status = true;
getExtraConnection();
System.out.println("connected:" + status);
} catch (Exception e) {
status = false;
System.out.print(e.getMessage());
e.printStackTrace();
}
}
});
thread.start();
try {
thread.join();
} catch (Exception e) {
e.printStackTrace();
this.status = false;
}
}
public Connection getExtraConnection() {
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.postgresql.Driver");
c = DriverManager.getConnection(url, user, pass);
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM videos WHERE access_count=1;");
while (rs.next()) {
V_id1 = rs.getString("video_id");
//
// System.out.println("NAME = " + Name);
// System.out.println("BIO = " + Bio);
// System.out.println("PHONE = " + Phone);
System.out.println();
}
rs.close();
stmt.close();
c.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
System.out.println("Records created successfully");
return c;
}
}
}
Code from the main activity where FreeClassesAdapter is used - UiUxActivity.java:
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.athrved.masterclass.FetchData;
import com.athrved.masterclass.R;
import java.util.ArrayList;
import java.util.List;
public class UiuxActivity extends AppCompatActivity {
TextView abcde;
TextView ak;
String tit;
String urlname,videoID,tita;
RecyclerView dataList2;
List<String> titles2;
List<Integer> images2;
ImgAdapter2 imgAdapter2;
RecyclerView popRecycler;
RecyclerView.Adapter adapter1;
RecyclerView freeRecycler;
RecyclerView.Adapter adapter2;
RecyclerView menRecycler;
RecyclerView.Adapter adapter3;
RecyclerView allFewRecycler;
RecyclerView.Adapter adapter4;
ArrayList<UiuxAllClasses> allCourseList=new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_uiux);
getSupportActionBar().setTitle("UI UX Design");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.greyy)));
// videoID="_vAmKNin0QM";
// urlname="https://noembed.com/embed?url=https://www.youtube.com/watch?v="+videoID;
// tita= respo(urlname);
popRecycler = findViewById(R.id.r1popclass);
featuredRecycler();
freeRecycler=findViewById(R.id.r1freeclass);
freeturedRecycler( tit);
menRecycler=findViewById(R.id.r3menclass);
mentoredRecycler();
allFewRecycler=findViewById(R.id.r4fewalllist);
allfewRecycler();
dataList2 = findViewById(R.id.dataList2);
abcde = findViewById(R.id.tvv1);
ak=findViewById(R.id.ak);
titles2 = new ArrayList<>();
images2 = new ArrayList<>();
titles2.add("Visual Design");
titles2.add("UX Design");
titles2.add("Motion Design");
titles2.add("Prototyping");
titles2.add("3D Design");
titles2.add("Webflow");
images2.add(R.drawable.visuald_logo);
images2.add(R.drawable.uiux_logo);
images2.add(R.drawable.motiond_logo);
images2.add(R.drawable.mach_logo);
images2.add(R.drawable.threed_logo);
images2.add(R.drawable.iot_logo);
imgAdapter2 = new ImgAdapter2(this,titles2,images2);
GridLayoutManager gridLayoutManager = new GridLayoutManager(this,2,GridLayoutManager.VERTICAL,false);
dataList2.setLayoutManager(gridLayoutManager);
dataList2.setAdapter(imgAdapter2);
}
private void featuredRecycler(){
FetchData fetchData = new FetchData();
fetchData.execute();
popRecycler.setHasFixedSize(true);
popRecycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
ArrayList<PopHelperClass> popLocatio = new ArrayList<>();
popLocatio.add(new PopHelperClass(R.drawable.secndone, R.drawable.ai_logo,0,"Color and Color Theory -\nFundamentals of Visual Design","VISUAL DESIGN","Goutham Naik","Um3BhY0oS2c"));
popLocatio.add(new PopHelperClass(R.drawable.firstone, R.drawable.ai_logo, R.drawable.motiond_logo,"Color and Color Theory -\nFundamentals of Visual Design","UX DESIGN"," Goutham Naik, S. M. Sudhanva Acharya","_vAmKNin0QM"));
adapter1=new PopclassesAdapter(popLocatio);
popRecycler.setAdapter(adapter1);
}
private void freeturedRecycler(String tita){
freeRecycler.setHasFixedSize(true);
freeRecycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
ArrayList<FreeHelperClass> freeLocatio = new ArrayList<>();
freeLocatio.add(new FreeHelperClass(R.drawable.ai_logo,0,"Top UX Design Interview Questions","VISUAL DESIGN","S M Sudhanva Acharya"));
freeLocatio.add(new FreeHelperClass(R.drawable.ai_logo,0,"White Space in Design","VISUAL DESIGN","Abhinav Chikkara"));
adapter2=new FreeclassesAdapter(freeLocatio);
freeRecycler.setAdapter(adapter2);
}
private void mentoredRecycler(){
menRecycler.setHasFixedSize(true);
menRecycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
ArrayList<MenHelperClass> menLocatio = new ArrayList<>();
menLocatio.add(new MenHelperClass(R.drawable.oneman,"Goutam Naik","CEO, AthrV-Ed"));
menLocatio.add(new MenHelperClass(R.drawable.twoman,"S M Sudhanva Acharya", "Product Designer, AthrV-Ed"));
menLocatio.add(new MenHelperClass(R.drawable.threeman,"Abhinav Chikkara", "Founder, 10kilogram"));
adapter2=new MenAdapter(menLocatio);
menRecycler.setAdapter(adapter2);
}
private void allfewRecycler(){
allFewRecycler.setHasFixedSize(true);
allFewRecycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
ArrayList<FewAllHelperClass> fewAllLocatio = new ArrayList<>();
fewAllLocatio.add(new FewAllHelperClass(R.drawable.webflow_l, R.drawable.ai_logo,"Playing with Grid-\nWeb Design Fundamentals","WEBFLOW","Goutham Naik"));
fewAllLocatio.add(new FewAllHelperClass(R.drawable.protopie_l, R.drawable.ai_logo,"Protopie for Prototyping","PROTOTYPING\n","Abhinav Chikkara"));
fewAllLocatio.add(new FewAllHelperClass(R.drawable.afepluslot_l, R.drawable.ai_logo,"Introduction to After Effects\nand Lottie Files","MOTION DESIGN","S.M Sudhanva Acharya"));
adapter4=new FewAllAdapter(fewAllLocatio);
allFewRecycler.setAdapter(adapter4);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
}
Are you storing the video in your DB as a BLOB / CLOB.
What if you store the video in a different location, and save the address of the location in your DB. This way Db has to return a string, and UI / consumer can take care of rendering from the path.

How to use a listview in android studio to search based off a return of a class function?

I am learning java and android studio and I am trying to make a menu with each food item being an individual class with a set of allergens either having a true or false value. I add the objects of each class into an ArrayList to display them using a list view. I have implemented a search bar that works correctly, however I am trying to modify the onTextChanged function so if for example the user types in "gluten" it will return all food items that DO NOT contain that allergen.
My code is as follows below, with the commented out sections being some testing I have attempted
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.text.Editable;
import android.text.TextWatcher;
import java.util.ArrayList;
import java.util.*;
import android.widget.EditText;
import android.widget.ArrayAdapter;
import android.widget.ListView;
//Test Classes for now will be added into a different file once working as intended.
class Pad_Thai{
public
String name = "Pad Thai";
boolean gluten = false;
boolean shellfish = true;
}
class Fried_Rice{
public
String name = "Fried Rice";
boolean gluten = true;
boolean shellfish = true;
}
class Beef_Broc{
public
String name = "Beef & Broc";
boolean gluten = true;
boolean shellfish = true;
}
//Testing Function to test if an object of a class has that allergen
//public class hasGluten {
// public boolean yes(boolean []arr) {
// for (int i = 0; i < arr.length; i++) {
// if (arr[i] == true) {
// }
// }
// return true;
// }
//}
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private ArrayAdapter adapter;
private ArrayAdapter adapter2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView list = (ListView) findViewById(R.id.theList);
EditText theFilter = (EditText) findViewById(R.id.searchFilter);
Log.d(TAG, "onCreate: Started.");
//Creating Objects of the Specified classes
Pad_Thai obj = new Pad_Thai();
Beef_Broc obj2= new Beef_Broc();
Fried_Rice obj3= new Fried_Rice();
//array of an object of classes
ArrayList<String> food = new ArrayList<>();
//testing array
ArrayList<String> names = new ArrayList<>();
food.add(obj.name);
food.add(obj2.name);
food.add(obj3.name);
names.add("Orange Chicken");
names.add("Pad Thai");
names.add("Fried Rice");
names.add("Beef and Broc");
names.add("Special Tempora");
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, food);
adapter2 = new ArrayAdapter(this, android.R.layout.simple_list_item_1, names);
list.setAdapter(adapter);
theFilter.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
(MainActivity.this).adapter.getFilter().filter(charSequence);
//int textlength = charSequence.length();
//ArrayList<food> tempArrayList = new ArrayList<food>();
//for (food c : tempArrayList) {
// if (c.hasGluten() == false) {
// tempArrayList.add(c);
// }
//}
//mAdapter = new food(activity, tempArrayList);
//lv.setAdapter(madapter);
String gluten = "gluten";
if (charSequence == gluten)
{
(MainActivity.this).adapter2.getFilter();
}
}
#Override
public void afterTextChanged(Editable editable) {
}
});
}
}

Handle empty recycle viewr within fragments

I am trying to make an application where using Recycle View and Volley to get data from server and also I used Navigation drawer and fragments,Everything working fine except When no data on recycle-view I want to show a notice like "there is no data!"I searched over internet multiple times but haven't get a proper solution or I couldn't understand properly because I am totally beginner.
bellow is my java files
1.Adapter
package com.eworld.myapplication;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.squareup.picasso.Picasso;
import java.util.List;
public class ExchangesAdapter extends RecyclerView.Adapter<ExchangesViewHolder> {
private List<ExchangesSetterGetter>exchangeList;
private Context context;
public ExchangesAdapter(List<ExchangesSetterGetter> exchangeList, Context context) {
this.exchangeList = exchangeList;
this.context = context;
}
#NonNull
#Override
public ExchangesViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view=LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cardlayout,viewGroup,false);
ExchangesViewHolder viewHolder=new ExchangesViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull ExchangesViewHolder exchangesViewHolder, int i) {
String status="";
final ExchangesSetterGetter exchangesPosition=exchangeList.get(i);
if (exchangesPosition.getStatus().equals("1")) {
status = "Awaiting Confirmation";
} else if (exchangesPosition.getStatus().equals("2")) {
status = "Awaiting Payment";
} else if (exchangesPosition.getStatus().equals("3")) {
status = "Processing";
} else if (exchangesPosition.getStatus().equals("4")) {
status = "proceed";
} else if (exchangesPosition.getStatus().equals("5")) {
status = "Timeout";
} else if (exchangesPosition.getStatus().equals("6")) {
status = "Denied";
} else if (exchangesPosition.getStatus().equals("7")) {
status = "Canceled";
} else if (exchangesPosition.getStatus().equals("8")) {
status = "Unknown";
}
exchangesViewHolder.gatewayFrom.setText(exchangesPosition.getAmountFrom() + " " + exchangesPosition.getCurrencyFrom() + " " + exchangesPosition.getExchangeFrom());
exchangesViewHolder.gatewayTo.setText(exchangesPosition.getAmountTo() + " " + exchangesPosition.getCurrencyTo() + " " + exchangesPosition.getExchangeTo());
exchangesViewHolder.status.setText(status);
Picasso.get().load("https://eworld.ltd/" + exchangesPosition.getImgSend()).into(exchangesViewHolder.imgSendFrom);
Picasso.get().load("https://eworld.ltd/" + exchangesPosition.getImgReceived()).into(exchangesViewHolder.imgSendTo);
}
#Override
public int getItemCount() {
return exchangeList.size();
}
}
2.View Holder
package com.eworld.myapplication;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class ExchangesViewHolder extends RecyclerView.ViewHolder {
ImageView imgSendFrom,imgSendTo;
TextView gatewayFrom,gatewayTo,status;
public ExchangesViewHolder(#NonNull View itemView) {
super(itemView);
imgSendFrom=itemView.findViewById(R.id.img1);
imgSendTo=itemView.findViewById(R.id.img2);
gatewayFrom=itemView.findViewById(R.id.tv1);
gatewayTo=itemView.findViewById(R.id.tv2);
status=itemView.findViewById(R.id.tv3);
}
}
3.Getter and Setter(Data model)
package com.eworld.myapplication;
public class ExchangesSetterGetter {
private String exchangeFrom,exchangeTo,status,imgSend,imgReceived,currencyFrom,currencyTo,amountFrom,amountTo;
public ExchangesSetterGetter(String exchangeFrom, String exchangeTo, String status, String imgSend, String imgReceived, String currencyFrom, String currencyTo, String amountFrom, String amountTo) {
this.exchangeFrom = exchangeFrom;
this.exchangeTo = exchangeTo;
this.status = status;
this.imgSend = imgSend;
this.imgReceived = imgReceived;
this.currencyFrom = currencyFrom;
this.currencyTo = currencyTo;
this.amountFrom = amountFrom;
this.amountTo = amountTo;
}
public String getCurrencyFrom() {
return currencyFrom;
}
public void setCurrencyFrom(String currencyFrom) {
this.currencyFrom = currencyFrom;
}
public String getCurrencyTo() {
return currencyTo;
}
public void setCurrencyTo(String currencyTo) {
this.currencyTo = currencyTo;
}
public String getAmountFrom() {
return amountFrom;
}
public void setAmountFrom(String amountFrom) {
this.amountFrom = amountFrom;
}
public String getAmountTo() {
return amountTo;
}
public void setAmountTo(String amountTo) {
this.amountTo = amountTo;
}
public String getExchangeFrom() {
return exchangeFrom;
}
public void setExchangeFrom(String exchangeFrom) {
this.exchangeFrom = exchangeFrom;
}
public String getExchangeTo() {
return exchangeTo;
}
public void setExchangeTo(String exchangeTo) {
this.exchangeTo = exchangeTo;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getImgSend() {
return imgSend;
}
public void setImgSend(String imgSend) {
this.imgSend = imgSend;
}
public String getImgReceived() {
return imgReceived;
}
public void setImgReceived(String imgReceived) {
this.imgReceived = imgReceived;
}
}
4.And finally my fragment Activity with recycle-view
package com.eworld.myapplication;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
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 org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class ExchangesFrag extends Fragment {
RecyclerView recyclerView;
ExchangesAdapter adapter;
List<ExchangesSetterGetter> listItems;
SharedPrefManager sharedPreferences;
int uid;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View exchanges=inflater.inflate(R.layout.exchanges_layout,container,false);
recyclerView=exchanges.findViewById(R.id.rview);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
listItems=new ArrayList<>();
sharedPreferences=new SharedPrefManager(getActivity());
uid = sharedPreferences.getUser().getId();
loadData();
return exchanges;
}
public void loadData() {
StringRequest stringRequest=new StringRequest(Request.Method.GET, URLs.url+uid, 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++) {
JSONObject receive = jsonArray.getJSONObject(i);
ExchangesSetterGetter exchangesSetterGetter = new ExchangesSetterGetter(
receive.getString("exchangeFrom"),
receive.getString("exchangeTo"),
receive.getString("status"),
receive.getString("imgSend"),
receive.getString("imgReceive"),
receive.getString("sendCurrency"),
receive.getString("receiveCurrency"),
receive.getString("amount_send"),
receive.getString("amount_receive")
);
listItems.add(exchangesSetterGetter);
}
adapter = new ExchangesAdapter(listItems, getContext());
recyclerView.setAdapter(adapter);
} catch(JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(),"error on volley",Toast.LENGTH_LONG).show();
}
});
RequestQueue queue= Volley.newRequestQueue(getContext());
queue.add(stringRequest);
}
}
You can handle the empty state by having a TextView in your layout, which switch its visibility state depending upon the array size you are getting in your response as:
JSONArray jsonArray = jsonObject.getJSONArray("data");
if (jsonArray.length() > 0) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject receive = jsonArray.getJSONObject(i);
ExchangesSetterGetter exchangesSetterGetter = new ExchangesSetterGetter(
receive.getString("exchangeFrom"),
receive.getString("exchangeTo"),
receive.getString("status"),
receive.getString("imgSend"),
receive.getString("imgReceive"),
receive.getString("sendCurrency"),
receive.getString("receiveCurrency"),
receive.getString("amount_send"),
receive.getString("amount_receive")
);
listItems.add(exchangesSetterGetter);
}
adapter = new ExchangesAdapter(listItems, getContext());
recyclerView.setAdapter(adapter);
recyclerView.setVisibilty(View.VISIBLE);
noDataText.setVisibilty(View.GONE);
} else {
recyclerView.setVisiblity(View.GONE);
noDataText.setVisiblity(View.VISIBLE);
}
Add an extra textview in your fragment xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/tv_no_data"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:textSize="22sp"
android:visibility="gone" />
<android.support.v7.widget.RecyclerView
android:id="#+id/rv_ride_list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
And then in your activity
JSONArray jsonArray = jsonObject.getJSONArray("data");
if(jsonArray.length() > 0){
//process data and initialize adapter
}else{
//Set Text view visible
}
There is a simple solution for that inside your fragment xml where recycler view is being loaded take a relative layout and add a textview with your desired message at last and set it's alignment as per your requirement and inside on create of your fragment set visiblity of your text view to View.INVISIBLE and later on after api is called simply pass an if condition stating that
if(response==null){ textview.setVisiblity = View.Visible}
The way I like to handle this is to wrap your RecyclerView and your NoContentView (this can be whatever you like) in a ViewFlipper like so
<ViewFlipper>
</RecyclerView>
<NoContentView>
</NoContentView>
</ViewFlipper>
Then all you do is to check to see if you have list items and display the appropriate child layout of the ViewFlipper
if(listItems.size() == 0)
{
viewFlipper.setDisplayedChild(1)
}

Recycler view list items are showing duplicate few items at the bottom of listview

I have one recycle list view .In this I have one button .on click list view item button shows.On button click I hit one api to perform action .After performing action ,at the bottom of list automatically one item get repeat. when ever I perform api hit action same time items add at the bottom of list .Like as I perform api hit action 4 times then every time one-one item get add at the bottom of list . Please provide me solution to resolve this.
Below I'm providing code of my adapter class :-
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.VolleyError;
import com.dockedinDoctor.app.R;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import pojo.AvailableTimeSlots;
import pojo.GetBlockedTimings;
import pojo.GetDoctorScheduleDetail;
import utils.Common;
import utils.ItemClickListener;
import utils.NetworkManager;
import utils.NetworkResponseListenerJSONObject;
import utils.SessionManager;
import utils.ShowMessage;
import static utils.Common.createProgressDialog;
public class MyScheduleAdapter extends RecyclerView.Adapter<MyScheduleAdapter.ViewHolder> {
private static final String TAG = "MyScheduleTwoAdapter";
private ArrayList<GetDoctorScheduleDetail> getDoctorScheduleDetails;
private ArrayList<GetBlockedTimings> getBlockedTimingses = new ArrayList<>();
private ArrayList<AvailableTimeSlots> availableTimeSlotses = new ArrayList<>();
Context context;
private LayoutInflater inflater = null;
private int mSelectedItemPosition = -1;
Activity parentActivity;
ProgressDialog pd;
int fk_time_id;
int fk_schedule_id;
int fkscheduleid;
int getFk_schedule_id;
int block_time_slot_id;
int time_slot_id;
String DateofSlot;
String BlockDateOfSlot;
int blockid;
SessionManager manager = new SessionManager();
int Doc_Id;
ArrayList<Integer> compare= new ArrayList<Integer>();
ArrayList<Integer> compare_fk= new ArrayList<Integer>();
public MyScheduleAdapter(Context context, ArrayList<GetDoctorScheduleDetail> getDoctorScheduleDetails) {
this.context = context;
this.getDoctorScheduleDetails = getDoctorScheduleDetails;
inflater = LayoutInflater.from(context);
// setHasStableIds(true);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.row_item_get_doctor_schedule, parent, false);
MyScheduleAdapter.ViewHolder holder = new MyScheduleAdapter.ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
final GetDoctorScheduleDetail pojo = getDoctorScheduleDetails.get(position);
fkscheduleid = pojo.getScheduleId();
DateofSlot = pojo.getDateOfSlot();
try {
Doc_Id = manager.getPreferencesInt(context, "DocId");
Log.e(TAG, "DOCID" + Doc_Id);
holder.bindDataWithViewHolder(pojo, position);
//getting data from availavle timeslots
holder.tv_time_of_slot.setText(pojo.getAvailableTimeSlots().get(position).getTimeOfSlot());
time_slot_id = pojo.getAvailableTimeSlots().get(position).getTimeSlotId();
//want to ge
block_time_slot_id = pojo.getGetBlockedTimings().get(position).getFkTimeId();
BlockDateOfSlot = pojo.getGetBlockedTimings().get(position).getBlockDateOfSlot();
blockid = pojo.getGetBlockedTimings().get(position).getBlockId();
Log.e(TAG, "values_blockk" + time_slot_id +" "+ block_time_slot_id);
compare.add(time_slot_id);//compare is an arraylist using to save Availablearray-->timeslot id
compare_fk.add(block_time_slot_id);//compare_fk is an arraylist using to save getblocktimeid-->fktime id
Log.e(TAG, "compare" + compare);
Log.e(TAG, "compare_fk" + compare_fk);
/*erlier I was using this*/
/*ArrayList<Integer> x = compare;
ArrayList<Integer> y = compare_fk;
for (int i = 0; i < x.size(); i++) {
Integer xval = y.get(i);
for (int j = 0; j < y.size(); j++) {
if (xval.equals(x.get(j))) {
Toast.makeText(context,"same_list"+y.get(j),Toast.LENGTH_SHORT).show();
holder.tv_time_of_slot.setTextColor(Color.RED);
}
}
}*/
int array1Size = compare.size();
int array2Size = compare_fk.size();
if (compare.size() > compare_fk.size()) {
int k = 0;
for (int i = 0; i < compare_fk.size(); i++) {
if (((Integer)compare.get(i)).equals((Integer)compare_fk.get(i))) {
System.out.println((Integer)compare_fk.get(i));
Log.e("values_adapter", String.valueOf(((Integer)compare_fk.get(i))));
}
k = i;
}
}
else {
int k = 0;
for (int i = 0; i < compare.size(); i++) {
if (((Integer)compare.get(i)).equals((Integer) compare_fk.get(i))) {
System.out.println((Integer) compare.get(i));
Log.e("values_adapter11",String.valueOf(((Integer)compare.get(i))));
}
k = i;
}
}
if (time_slot_id == block_time_slot_id)
{
holder.tv_time_of_slot.setTextColor(Color.RED);
}
if (!(pojo.getGetBlockedTimings().get(position).getBlockDateOfSlot().equals("")))
{
holder.tv_d.setText(pojo.getGetBlockedTimings().get(position).getBlockDateOfSlot());
holder.tv_b.setText(pojo.getGetBlockedTimings().get(position).getBlockId());
}
} catch (Exception e) {
e.printStackTrace();
e.getMessage();
}
// //iterate on the general list
// for (int i = 0; i < availableTimeSlotses.size(); i++) {
// int timeSlotId = availableTimeSlotses.get(i).getTimeSlotId();
// if (getFk_time_id == timeSlotId) {
//
// holder.tv_time_of_slot.setText(pojo.getDateOfSlot());
// }
// }
// block api
holder.btn_block.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog lDialog = new Dialog(context);
lDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
lDialog.setCancelable(false);
lDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
lDialog.getWindow().setDimAmount(.7f);
lDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
lDialog.getWindow().setElevation(4);
}
lDialog.setContentView(R.layout.popup_no_yes);
TextView tv_titiel = (TextView) lDialog.findViewById(R.id.tv_titiel);
TextView textMsg = (TextView) lDialog.findViewById(R.id.popup_msgs);
Button btnno = (Button) lDialog.findViewById(R.id.popup_no_btn);
Button btnyes = (Button) lDialog.findViewById(R.id.popup_yes_btn);
btnno.setTransformationMethod(null);
btnyes.setTransformationMethod(null);
tv_titiel.setText("Schedule");
textMsg.setText("Are you sure you want to block this slot?");
btnno.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
lDialog.dismiss();
}
});
btnyes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent("notification_fragment"));
slotBlockingApi(fkscheduleid, time_slot_id);
lDialog.dismiss();
}
});
lDialog.show();
}
});
}
#Override
public int getItemCount() {
return getDoctorScheduleDetails.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
public void slotBlockingApi(int _fk_schedule_id, int _fk_time_id) {
isOnline();
pd = createProgressDialog(context);
pd.show();
final String requestBody = "'{\"fkScheduledId\":\"" + _fk_schedule_id +
"\",\"fkTimeId\":\"" + _fk_time_id +
"\",\"DoctorId\":\"" + Doc_Id +
"\"}'";
Log.e(TAG, "requset body of slotBlockingApi : " + requestBody);
NetworkManager.getInstance(context).makeNetworkRequestForJSON(
Request.Method.POST,
Common.BASE_URL + "/PostDoctorCheckForAppointmentBeforeSlotBlocking",
null,
requestBody,
null,
new NetworkResponseListenerJSONObject() {
#Override
public void onDataReceived(Object data) {
pd.dismiss();
Log.e(TAG, "response of slotBlockingApi : " + data.toString());
try {
JSONObject jsonObject = new JSONObject(data.toString());
JSONObject ResponseJsonObject1 = jsonObject.getJSONObject("Response");
int ResponseCode = ResponseJsonObject1.getInt("ResponseCode");
String ResponseText = ResponseJsonObject1.getString("ResponseText");
// JSONObject jsonObjectDetail = jsonObject.getJSONObject("Detail");
// Log.e(TAG, "jsonObjectDetail : " + jsonObjectDetail);
// int doc_id = jsonObjectDetail.getInt("DocId");
// if (ResponseText == "No Appointment" || ResponseText.equals("No Appointment") || ResponseText.equalsIgnoreCase("No Appointment")) {
if (ResponseText == "No Appointment" || ResponseText.equals("No Appointment") || ResponseText.equalsIgnoreCase("No Appointment")) {
// if (ResponseText =="No Appointment" || ResponseText.equals("No Appointment")) {
pd = createProgressDialog(context);
pd.show();
final String requestBody = "'{\"utcTimeOffset\":\"" + "330" +
"\",\"BlockedScheduledDate\":\"" + DateofSlot +
"\",\"fkScheduledId\":\"" + fkscheduleid +
"\",\"fkTimeId\":\"" + time_slot_id +
"\"}'";
Log.e(TAG, "requset body of slotBlocking: " + requestBody);
NetworkManager.getInstance(context).makeNetworkRequestForJSON(
Request.Method.POST,
Common.BASE_URL + "/PostDoctorBlockTimeSlot",
null,
requestBody,
null,
new NetworkResponseListenerJSONObject() {
#Override
public void onDataReceived(Object data) {
pd.dismiss();
new ShowMessage(context, "Block Slot","Time slot blocked Successfully");
Log.e(TAG, "response of slotBlocking: " + data.toString());
}
#Override
public void onDataFailed(VolleyError error) {
pd.dismiss();
String json = null;
NetworkResponse response = error.networkResponse;
if (response != null && response.data != null) {
switch (response.statusCode) {
case 302:
Toast.makeText(context, "No Internet Connection Found.", Toast.LENGTH_SHORT).show();
break;
}
//Additional cases
}
}
});
} else {
final Dialog lDialog = new Dialog(context);
lDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
lDialog.setCancelable(false);
lDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
lDialog.getWindow().setDimAmount(.7f);
lDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
lDialog.getWindow().setElevation(4);
}
lDialog.setContentView(R.layout.custom_popup);
TextView textTitle = (TextView) lDialog.findViewById(R.id.popup_title);
TextView textMsg = (TextView) lDialog.findViewById(R.id.popup_msg);
Button okButton = (Button) lDialog.findViewById(R.id.popup_ok_btn);
okButton.setTransformationMethod(null);
textTitle.setText("Schedule");
textMsg.setText("An appointment has been booked on this slot.");
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
lDialog.dismiss();
}
});
lDialog.show();
}
// else if (ResponseCode == 0 || ResponseCode == 2) {
// new ShowMessage(context, ResponseText);
// }
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onDataFailed(VolleyError error) {
pd.dismiss();
String json = null;
NetworkResponse response = error.networkResponse;
if (response != null && response.data != null) {
switch (response.statusCode) {
case 302:
Toast.makeText(context, "No Internet Connection Found.", Toast.LENGTH_SHORT).show();
break;
}
//Additional cases
}
}
});
}
public boolean isOnline() {
ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMgr.getActiveNetworkInfo();
if (netInfo == null || !netInfo.isConnected() || !netInfo.isAvailable()) {
new ShowMessage(context, "Network error","Internet not available, Cross check your internet connectivity and try again");
}
return true;
}
/**
* VIEW HOLDER CLASS DEFINE HERE
*/
public class ViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.ll_row_item_get_doctor_schedule)
LinearLayout ll_row_item_get_doctor_schedule;
#BindView(R.id.tv_time_of_slot)
TextView tv_time_of_slot;
#BindView(R.id.btn_block)
Button btn_block;
#BindView(R.id.btn_unblock)
Button btn_unblock;
#BindView(R.id.tv_d)
TextView tv_d;
#BindView(R.id.tv_b)
TextView tv_b;
GetDoctorScheduleDetail doctorScheduleDetail = null;
ItemClickListener clickListener;
private ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
ll_row_item_get_doctor_schedule.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Handling for background selection state changed
int previousSelectState = mSelectedItemPosition;
mSelectedItemPosition = getAdapterPosition();
//notify previous selected item
notifyItemChanged(previousSelectState);
//notify new selected Item
notifyItemChanged(mSelectedItemPosition);
//Your other handling in onclick
}
});
}
public void setClickListener(ItemClickListener itemClickListener) {
this.clickListener = itemClickListener;
}
#OnClick
public void onClickMethod(View v) {
clickListener.onClick(v, getPosition(), false);
}
public void bindDataWithViewHolder(GetDoctorScheduleDetail schedulePojo, int currentPosition) {
this.doctorScheduleDetail = schedulePojo;
//Handle selection state in object View.
if (currentPosition == mSelectedItemPosition) {
btn_block.setVisibility(View.VISIBLE);
} else {
btn_block.setVisibility(View.GONE);
}
//other View binding logics like setting text , loading image etc.
}
}
}

How to pass data collected in arraylist from json asset file in one activity having recyclerview to another activity again having recycler view?

I have an activity named Cardview Activity which has a recycler view associated with it and i am fetching data from a JSON asset file in that. But now when i click on an item of Cardview Activity, I want to send data related to that item only to another activity i.e. People_List_Activity which is again having a recyclerView.
CardViewActivity.java
package com.example.android.directory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
public class CardViewActivity extends AppCompatActivity {
Toolbar mActionBarToolbar;
private RecyclerView mainRecyclerView;
private RecyclerView.Adapter mainAdapter;
private RecyclerView.LayoutManager mainLayoutManager;
private static String LOG_TAG = "CardViewActivity";
EditText inputSearchMain;
private ArrayList<CategoryModel.CategoryList> categoryLists;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_card_view);
mActionBarToolbar = (Toolbar) findViewById(R.id.tool_bar);
mActionBarToolbar.setTitle("Telephone Directory");
mActionBarToolbar.setLogo(R.drawable.toolbar_logo);
mActionBarToolbar.setTitleMargin(5,2,2,2);
setSupportActionBar(mActionBarToolbar);
categoryLists=new ArrayList<CategoryModel.CategoryList>();
categoryLists.addAll(getmcategoryset());
mainRecyclerView=(RecyclerView)findViewById(R.id.recyclerView_Main);
mainRecyclerView.setHasFixedSize(true);
mainLayoutManager=new LinearLayoutManager(this);
mainRecyclerView.setLayoutManager(mainLayoutManager);
mainAdapter=new RecyclerViewAdapterMain(getmcategoryset());
mainRecyclerView.setAdapter(mainAdapter);
inputSearchMain = (EditText) findViewById(R.id.inputSearchMain);
addTextListener();
}
public void addTextListener(){
inputSearchMain.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence query, int start, int before, int count) {
query = query.toString().toLowerCase();
final ArrayList<CategoryModel.CategoryList> filteredList = new ArrayList<CategoryModel.CategoryList>();
for (int i = 0; i < categoryLists.size(); i++) {
final String text = categoryLists.get(i).getCategory_name().toLowerCase();
if (text.contains(query)) {
filteredList.add(categoryLists.get(i));
}
}
mainRecyclerView.setLayoutManager(new LinearLayoutManager(CardViewActivity.this));
mainAdapter = new RecyclerViewAdapterMain(filteredList);
mainRecyclerView.setAdapter(mainAdapter);
mainAdapter.notifyDataSetChanged(); // data set changed
}
});
}
private ArrayList<CategoryModel.CategoryList> getmcategoryset() {
try {
ArrayList<CategoryModel.CategoryList>categoryList = new ArrayList<CategoryModel.CategoryList>();
JSONObject jsonObject = new JSONObject(readJSONFromAsset());
JSONArray categoryArray = jsonObject.getJSONArray("Category");
Log.d("getmcategoryset", "category count: "+categoryArray.length());
for (int i = 0; i < categoryArray.length(); i++)
{
JSONObject job = categoryArray.getJSONObject(i);
int categoryId = job.getInt("Category_id");
String categoryName = job.getString("Category_name");
//this is for email array
ArrayList<String> emails = new ArrayList<>();
JSONArray emailArray = job.getJSONArray("Emails");
for (int j = 0; j< emailArray.length(); j++){
emails.add(emailArray.getString(j));
}
//This i for Epabx array
ArrayList<String> epabx = new ArrayList<>();
JSONArray epabxArray = job.getJSONArray("Epabx");
for (int j = 0; j < epabxArray.length(); j++){
epabx.add(epabxArray.getString(j));
}
//This i for Category_Fax array
ArrayList<String> category_Fax = new ArrayList<>();
JSONArray category_FaxJson = job.getJSONArray("Category_Fax");
for (int j = 0; j < category_FaxJson.length(); j++){
category_Fax.add(category_FaxJson.getString(j));
}
//This i for Persons array
ArrayList<CategoryModel.Persons> personsList = new ArrayList<>();
JSONArray personsArray = job.getJSONArray("Persons");
for (int j = 0; j < personsArray.length(); j++){
JSONObject jobIn = personsArray.getJSONObject(j);
int Person_ID = jobIn.getInt("Person_ID");
String Name = jobIn.getString("Name");
String Designation = jobIn.getString("Designation");
String Office_Phone = jobIn.getString("Office_Phone");
String Residence_Phone = jobIn.getString("Residence_Phone");
String VOIP = jobIn.getString("VOIP");
String Address = jobIn.getString("Address");
//this is for Fax array
ArrayList<String>Fax = new ArrayList<>();
JSONArray fax = jobIn.getJSONArray("Fax");
for (int k=0; k < fax.length(); k++)
{
// JSONObject jobI = fax.getString(k);
Fax.add(fax.getString(k));
}
String Ext = jobIn.getString("Ext");
personsList.add(new CategoryModel.Persons(Person_ID, Name, Designation, Office_Phone, Residence_Phone,
VOIP, Address, Fax, Ext));
}
//here your Category[] value store in categoryArrayList
categoryList.add(new CategoryModel.CategoryList(categoryId, categoryName, emails, epabx, category_Fax, personsList));
Log.i("categoryList size = ", ""+categoryArray.length());
}
if (categoryList != null)
{
Log.i("categoryList size = ", ""+categoryArray.length());
}
return categoryList;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onResume() {
super.onResume();
}
public String readJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("DirectoryData.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
}
RecyclerViewAdapterMain
package com.example.android.directory;
import android.content.Intent;
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.TextView;
import java.util.ArrayList;
import java.util.Arrays;
/**
* Created by Android on 3/17/2017.
*/
public class RecyclerViewAdapterMain extends RecyclerView.Adapter<RecyclerViewAdapterMain.CategoryObjectHolder> {
private static String LOG_TAG = "categoryRecyclrVwAdptr";
private ArrayList<CategoryModel.CategoryList> mcategoryset;
private static CategoryClickListener categoryClickListener;
public static class CategoryObjectHolder extends RecyclerView.ViewHolder {
TextView category_name;
public CategoryObjectHolder(View itemView){
super(itemView);
category_name=(TextView)itemView.findViewById(R.id.category_name);
/*category_emails=(TextView)itemView.findViewById(R.id.category_emails);
category_epabx=(TextView)itemView.findViewById(R.id.category_epabx);
category_fax=(TextView)itemView.findViewById(R.id.category_fax);*/
Log.i(LOG_TAG, "Adding Listener");
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(CardViewActivity.this,PeopleListActivity.class);
}
});
}
public RecyclerViewAdapterMain(ArrayList<CategoryModel.CategoryList> myDataset) {
mcategoryset = myDataset;
}
public CategoryObjectHolder onCreateViewHolder(ViewGroup parent,int viewType){
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view_row_main_activity,parent,false);
CategoryObjectHolder categoryObjectHolder=new CategoryObjectHolder(view);
return categoryObjectHolder;
}
#Override
public void onBindViewHolder(CategoryObjectHolder holder, int position) {
holder.category_name.setText(mcategoryset.get(position).getCategory_name());
}
public void addItem(CategoryModel.CategoryList dataObj, int index) {
mcategoryset.add(index, dataObj);
notifyItemInserted(index);
}
public void deleteItem(int index) {
mcategoryset.remove(index);
notifyItemRemoved(index);
}
#Override
public int getItemCount() {
return mcategoryset.size();
}
public interface CategoryClickListener {
public void onItemClick(int position, View v);
}
}
People_List_Activity.java
package com.example.android.directory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
public class PeopleListActivity extends AppCompatActivity {
Toolbar mActionBarToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_people_list);
mActionBarToolbar = (Toolbar) findViewById(R.id.tool_bar);
mActionBarToolbar.setTitle("Staff List");
mActionBarToolbar.setLogo(R.drawable.toolbar_logo);
mActionBarToolbar.setTitleMargin(5,2,2,2);
setSupportActionBar(mActionBarToolbar);
}
}
RecyclerViewAdapter_People.java
package com.example.android.directory;
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.TextView;
/**
* Created by Android on 3/20/2017.
*/
public class RecyclerViewAdapter_People extends RecyclerView.Adapter<RecyclerViewAdapter_People.PeopleObjectHolder> {
private static String TAG = "peopleRecyclrVwAdptr";
public static class PeopleObjectHolder extends RecyclerView.ViewHolder{
TextView peopleName,peopleDesignation;
public PeopleObjectHolder(View itemView) {
super(itemView);
peopleName=(TextView)itemView.findViewById(R.id.people_name);
peopleDesignation=(TextView)itemView.findViewById(R.id.people_designation);
Log.d(TAG, "PeopleObjectHolder: ");
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
}
#Override
public PeopleObjectHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_people_list_row,parent,false);
PeopleObjectHolder peopleObjectHolder=new PeopleObjectHolder(view);
return peopleObjectHolder;
}
#Override
public void onBindViewHolder(RecyclerViewAdapter_People.PeopleObjectHolder holder, int position) {
}
#Override
public int getItemCount() {
return 0;
}
}
CategoryModel.java:
package com.example.android.directory;
import java.util.ArrayList;
/**
* Created by Android on 3/17/2017.
*/
public class CategoryModel {
private ArrayList<CategoryList>categoryList;
public ArrayList<CategoryList> getCategoryList() {
return categoryList;
}
public void setCategoryList(ArrayList<CategoryList> categoryList) {
this.categoryList = categoryList;
}
public static class CategoryList{
private int Category_id;
private String Category_name;
private ArrayList<String>Emails;
private ArrayList<String>Epabx;
private ArrayList<String>Category_Fax;
private ArrayList<Persons> persons;
public CategoryList(int category_id, String category_name,
ArrayList<String> emails, ArrayList<String> epabx, ArrayList<String> category_Fax,
ArrayList<Persons> persons) {
Category_id = category_id;
Category_name = category_name;
Emails = emails;
Epabx = epabx;
Category_Fax = category_Fax;
this.persons = persons;
}
public int getCategory_id() {
return Category_id;
}
public void setCategory_id(int category_id) {
Category_id = category_id;
}
public String getCategory_name() {
return Category_name;
}
public void setCategory_name(String category_name) {
Category_name = category_name;
}
public ArrayList<String> getEmails() {
return Emails;
}
public void setEmails(ArrayList<String> emails) {
Emails = emails;
}
public ArrayList<String> getEpabx() {
return Epabx;
}
public void setEpabx(ArrayList<String> epabx) {
Epabx = epabx;
}
public ArrayList<String> getCategory_Fax() {
return Category_Fax;
}
public void setCategory_Fax(ArrayList<String> category_Fax) {
Category_Fax = category_Fax;
}
public ArrayList<Persons> getPersons() {
return persons;
}
public void setPersons(ArrayList<Persons> persons) {
this.persons = persons;
}
}
public static class Persons{
private int Person_ID;
private String Name;
private String Designation;
private String Office_Phone;
private String Residence_Phone;
private String VOIP;
private String Address;
private ArrayList<String>Fax;
private String Ext;
public Persons(int person_ID, String name, String designation, String office_Phone,
String residence_Phone, String VOIP, String address, ArrayList<String> fax, String ext) {
Person_ID = person_ID;
Name = name;
Designation = designation;
Office_Phone = office_Phone;
Residence_Phone = residence_Phone;
this.VOIP = VOIP;
Address = address;
Fax = fax;
Ext = ext;
}
public int getPerson_ID() {
return Person_ID;
}
public void setPerson_ID(int person_ID) {
Person_ID = person_ID;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getDesignation() {
return Designation;
}
public void setDesignation(String designation) {
Designation = designation;
}
public String getOffice_Phone() {
return Office_Phone;
}
public void setOffice_Phone(String office_Phone) {
Office_Phone = office_Phone;
}
public String getResidence_Phone() {
return Residence_Phone;
}
public void setResidence_Phone(String residence_Phone) {
Residence_Phone = residence_Phone;
}
public String getVOIP() {
return VOIP;
}
public void setVOIP(String VOIP) {
this.VOIP = VOIP;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
public ArrayList<String> getFax() {
return Fax;
}
public void setFax(ArrayList<String> fax) {
Fax = fax;
}
public String getExt() {
return Ext;
}
public void setExt(String ext) {
Ext = ext;
}
}
}
how can i send the Person_Id, Name and Designation to the People_List_Activity ? Please help as i am stuck in the code.
You can send using Intent , by passing your data in Bundle and then pass Bundle into Intent Extras.When you go form one Activity to another .
Intent intent=new Intent(CardViewActivity.this,PeopleListActivity.class);
Bundle bundle = new Bundle();
bundle.putString("key1",value1);
bundle.putString("key2",value2);
bundle.putString("key3",value3);
intent.putExtras(bundle)
startActvity(intent);
And You can retrieve Data in next Activity OnCreate():
Bundle bundle = getIntent().getExtras();
String value1 = bundle.getString("key1");
String value2 = bundle.getString("key2");
String value3 = bundle.getString("key3");

Categories