duplicate list is adding to gridview in android - android

Hi in the below I am displaying calendarview.In calendarview I am selecting date and passing that date to GetAppointmentDate(selecteddate) if selecteddate and my date matches I am displaying gridview layout.but it is give multiple list with below .
Can any one help y duplicate list is displaying evrytime.
CalendarViewActivity.java:
public class CalendarViewActivity extends Activity implements DatetimeAdapter.MyItemClickListener{
private CalendarView mCalendarView;
private ProgressDialog progressDialog = null;
private ArrayList<GetData> getDataArrayList;
private ArrayList<GetSlots> getSlotsArrayList;
private GridView gridLayout;
private GetData getData2;
private GetSlots getSlots2;
private String Id,StartTime,SlotBooked,SlotDate,EndTime,SloteTime;
private DatetimeAdapter datetimeAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calendar_view);
gridLayout=findViewById(R.id.gridlayout);
getDataArrayList=new ArrayList<>();
getSlotsArrayList=new ArrayList<>();
mCalendarView = (CalendarView) findViewById(R.id.calendarView);
mCalendarView.setMinDate(System.currentTimeMillis() - 1000);
datetimeAdapter = new DatetimeAdapter(getApplicationContext(), getSlotsArrayList,this);
mCalendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
Calendar calendar = Calendar.getInstance();
int year1 = calendar.get(Calendar.YEAR);
int month1 = calendar.get(Calendar.MONTH);
int dayOfMonth1 = calendar.get(Calendar.DAY_OF_MONTH);
#Override
public void onSelectedDayChange(CalendarView CalendarView, int year1, int month1, int dayOfMonth1) {
String date = new SimpleDateFormat("MM", Locale.getDefault()).format(new Date());
SimpleDateFormat sdf = new SimpleDateFormat(date);
String selecteddate = (sdf.format(month1 + 1)) + "/" + dayOfMonth1 + "/" + year1;
GetAppointmentDate(selecteddate);
Toast.makeText(getApplicationContext(),selecteddate,Toast.LENGTH_LONG).show();
}
});
}
private void GetAppointmentDate(String outputcurrentdate) {
// progressDialog = new ProgressDialog(getApplicationContext());
// progressDialog.setIndeterminate(true);
// progressDialog.setMessage("Loading...");
// progressDialog.setCanceledOnTouchOutside(false);
// progressDialog.setCancelable(false);
// progressDialog.show();
String doctor_ids="13";
String HospitalId="PH:193";
final APIService service = RetroClass.getRetrofitInstance().create(APIService.class);
Call<GetAppointmentDateModel> call = service.GetAppointmentDate(doctor_ids,HospitalId);
Log.wtf("URL Called", call.request().url() + "");
call.enqueue(new Callback<GetAppointmentDateModel>() {
#Override
public void onResponse(Call<GetAppointmentDateModel> call, Response<GetAppointmentDateModel> response) {
Log.e("response", new Gson().toJson(response.body()));
if (response.isSuccessful()) {
Log.e("response", new Gson().toJson(response.body()));
GetAppointmentDateModel getAppointmentDateModel = response.body();
ArrayList<GetData> getData = getAppointmentDateModel.getGetAppointmentList();
for (GetData getData1 : getData) {
String date1 = getData1.getDate();
String id=getData1.getId();
DateFormat inputFormatter = new SimpleDateFormat("dd MMM yyyy HH:mm-HH:mm");
Date date = null;
try {
date = inputFormatter.parse(date1);
DateFormat outputFormatter = new SimpleDateFormat("MM/dd/yyyy");
String output = outputFormatter.format(date);
getData2=new GetData(id,output);
getDataArrayList.add(getData2);
Log.d("dateString",output);
ArrayList<GetSlots> getSlots = getData1.getData();
for (GetSlots getSlots1 : getSlots) {
Id=getSlots1.getId();
SlotDate=getSlots1.getDate();
StartTime=getSlots1.getStartTime();
EndTime=getSlots1.getEndTime();
SloteTime=getSlots1.getSlotTime();
SlotBooked=getSlots1.getSlotBooked();
getSlots2=new GetSlots(Id,SlotDate,StartTime,EndTime,SlotBooked,SloteTime);
getSlotsArrayList.add(getSlots2);
}
} catch (ParseException e) {
e.printStackTrace();
}
}
String current_date=getData2.getDate();
if(current_date.equals(outputcurrentdate)) {
gridLayout.setAdapter(datetimeAdapter);
datetimeAdapter.notifyDataSetChanged();
}
}
// progressDialog.dismiss();
}
#Override
public void onFailure(Call<GetAppointmentDateModel> call, Throwable t) {
Log.d("error", t.getMessage());
// progressDialog.dismiss();
}
});
}
#Override
public void myItemClick(int position) {
}
}

Your list - getSlotsArrayList is addding new values each time and it is not clearing anywhere. This is the same list that is passed to the adapter. so it is displaying multiple values.
Call clear method before this
getSlotsArrayList.clear();
GetAppointmentDate(selecteddate);

Related

data is not displaying in cart from firebase

Items is not displaying in cart from the firebase realtimedatabase I think I have initialized everything properly but its still not working its not showing any error but still not displaying it..
this is the map
This is the cart activity code
RecyclerView recyclerView;
cartAdapter cartadapt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_app_cart);
recyclerView = findViewById(R.id.recylervieww);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
String currentUserPhoneNumber = Paper.book().read(UserPhoneKey);
String timestamp = String.valueOf(System.currentTimeMillis());
FirebaseRecyclerOptions<Cartmodel> options =
new FirebaseRecyclerOptions.Builder<Cartmodel>()
.setQuery(FirebaseDatabase.getInstance().getReference().child("Cart List")
.child(UserPhoneKey)
, Cartmodel.class)
.build();
cartadapt = new cartAdapter(options);
recyclerView.setAdapter(cartadapt);
}
#Override
public void onStart() {
super.onStart();
cartadapt.startListening();
}
#Override
public void onStop() {
super.onStop();
cartadapt.stopListening();
}
this is the child from which data is need to be displayed from here we have to retrieve the data and display it in cart
private void addtocart() {
String saveCurrentDate, saveCurrentTime;
Calendar calForDate = Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat("MMM dd, yyyy");
saveCurrentDate = currentDate.format(calForDate.getTime());
SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss a");
saveCurrentTime = currentTime.format(calForDate.getTime());
final DatabaseReference cartListRef = FirebaseDatabase.getInstance().getReference().child("Cart List");
String timestamp = String.valueOf(System.currentTimeMillis());
double price = Double.parseDouble(emailholder.getText().toString().replace("₹", ""));
double quantityValue = Double.parseDouble(quantity.getText().toString());
double result = price * quantityValue;
Intent intent = getIntent();
String purl = intent.getStringExtra("purl");
final HashMap<String, Object> cartMap = new HashMap<>();
cartMap.put("productName",nameholder.getText().toString());
cartMap.put("productPrice",emailholder.getText().toString());
cartMap.put("productImage", purl);
cartMap.put("date",saveCurrentDate);
cartMap.put("time",saveCurrentTime);
cartMap.put("quantity",quantity.getText().toString());
cartMap.put("totalPrice",result);
String currentUserPhoneNumber = Paper.book().read(Prevalent.UserPhoneKey);
cartListRef.child(currentUserPhoneNumber)
.updateChildren(cartMap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(details.this, "Added to cart", Toast.LENGTH_SHORT).show();
}
});
}
}

I want push notification at the time set by the user while they add a task. After they set the Date and time I want to show notification

I want to send the user notification on that particular time and date after the user choose it while adding a new task. I want to get the notification title and description from the Firebase database and I want to display notification for every individual task.
Here is my code (HOW USER SELECT THE TIME AND DATE)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_task);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
mAuth = FirebaseAuth.getInstance();
mUser = mAuth.getCurrentUser () ;
OnlineUserID = mUser.getUid() ;
// Other Features Stuff
long Sysdate = System.currentTimeMillis();
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy");
String dateString = sdf.format(Sysdate);
timePickerBTN = findViewById(R.id.TimePickerBTN);
datePickerBTN = findViewById(R.id.DatePickerBTN);
calendar = Calendar.getInstance();
dateFormat = new SimpleDateFormat("dd/MM/yy");
date = (String) android.text.format.DateFormat.format("hh:mm aa", calendar);
timePickerBTN.setText(date);
datePickerBTN.setText(dateString);
timePickerBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TimePickerDialog timePickerDialog = new TimePickerDialog(NewTaskActivity.this, new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int hourOfDay, int Minute) {
TimeHour = hourOfDay;
TimeMinute = Minute;
Calendar calendarTime = Calendar.getInstance();
calendarTime.set(0,0,0, TimeHour, TimeMinute);
timePickerBTN.setText(android.text.format.DateFormat.format("hh:mm aa", calendarTime));
FINAL_TIME = timePickerBTN.getText().toString();
}
},12,0,false);
timePickerDialog.updateTime(TimeHour, TimeMinute);
timePickerDialog.show();
}
});
AND THE FOLLOWING CODE IS FOR SENDING DATA TO FIREBASE
DBrefrence = FirebaseDatabase.getInstance().getReference().child("tasks").child(OnlineUserID);
pdLoader = new ProgressDialog(this);
final EditText tskTitle = findViewById(R.id.taskTitle);
final EditText tskDescription = findViewById(R.id.taskDescription);
Button saveButton = findViewById(R.id.SaveTask_BTN);
datePickerBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DialogFragment datePicker = new com.veria.task.DatePicker();
datePicker.show(getSupportFragmentManager() ,"Pick a date");
}
});
saveButton.setOnClickListener((v) -> {
String mTask = tskTitle.getText().toString().trim();
String mDescription = tskDescription.getText().toString().trim();
String id = DBrefrence.push().getKey();
if (currentDate == null)
{
dateCurrentSelected = DateFormat.getDateInstance().format(new Date());
}
else if (currentDate!= null)
{
dateCurrentSelected = currentDate;
}
if (FINAL_TIME == null)
{
TimeCurrent = timePickerBTN.getText().toString();
}
else if (FINAL_TIME != null)
{
TimeCurrent = FINAL_TIME;
}
String Time = FINAL_TIME;
if (TextUtils.isEmpty(mTask))
{
tskTitle.setError("Title Required");
return;
}
if (TextUtils.isEmpty(mDescription))
{
tskDescription.setError("Description Required");
return;
}
else
{
pdLoader.setTitle("Task");
pdLoader.setMessage("Please wait");
pdLoader.setCanceledOnTouchOutside(false);
pdLoader.show();
Model model = new Model(mTask, mDescription, id, dateCurrentSelected, TimeCurrent);
DBrefrence.child(id).setValue(model).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful())
{
Intent intent = new Intent(NewTaskActivity.this, MainActivity.class);
startActivity(intent);
finish();
Toast.makeText(NewTaskActivity.this, "Task has been successfully added", Toast.LENGTH_SHORT).show();
pdLoader.dismiss();
}
else
{
Toast.makeText(NewTaskActivity.this, "Failed To Add Task", Toast.LENGTH_SHORT).show();
pdLoader.dismiss();
}
}
});
}
});
I don't know how to send notification on the time and date selected by user

List View not showing on android retrofit but Compiler allocated 4MB to compile void android.widget.TextView.<init>

I got a problem when showing data in list view with retrofit but the result like
and showing alert like this
2021-02-14 12:57:35.002 20138-20144/com.example.loginretrofit I/zygote: JIT allocated 71KB for compiled code of void android.widget.TextView.<init>(android.content.Context, android.util.AttributeSet, int, int)
2021-02-14 12:57:35.002 20138-20144/com.example.loginretrofit I/zygote: Compiler allocated 4MB to compile void android.widget.TextView.<init>(android.content.Context, android.util.AttributeSet, int, int)
and here is my activity book
public class activity_book extends AppCompatActivity {
DatePickerDialog picker;
private EditText startdate;
private EditText enddate;
Button btnGet;
private Spinner id_book;
TextView tvw;
public static ApiInterface apiInterface;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book);
startdate = (EditText) findViewById(R.id.startdate);
startdate.setInputType(InputType.TYPE_NULL);
enddate = (EditText) findViewById(R.id.enddate);
enddate.setInputType(InputType.TYPE_NULL);
id_book = findViewById(R.id.spinnerbook);
apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Api.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
Api api = retrofit.create(Api.class);
Call<List<Book>> call = api.getbooks();
call.enqueue(new Callback<List<Book>>() {
#Override
public void onResponse(Call<List<Book>> call, Response<List<Book>> response) {
List<Book> books = response.body();
String[] book = new String[books.size()];
for (int i = 0; i < books.size(); i++) {
book[i] = books.get(i).getId_book();
}
id_book.setAdapter(new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, book));
}
#Override
public void onFailure(Call<List<Book>> call, Throwable t) {
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
startdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Calendar cldr = Calendar.getInstance();
int day = cldr.get(Calendar.DAY_OF_MONTH);
int month = cldr.get(Calendar.MONTH);
int year = cldr.get(Calendar.YEAR);
// date picker dialog
picker = new DatePickerDialog(activity_book.this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
startdate.setText(dayOfMonth + "/" + (monthOfYear + 1) + "/" + year);
}
}, year, month, day);
picker.show();
}
});
enddate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Calendar cldr = Calendar.getInstance();
int day = cldr.get(Calendar.DAY_OF_MONTH);
int month = cldr.get(Calendar.MONTH);
int year = cldr.get(Calendar.YEAR);
// date picker dialog
picker = new DatePickerDialog(activity_book.this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
enddate.setText(dayOfMonth + "/" + (monthOfYear + 1) + "/" + year);
}
}, year, month, day);
picker.show();
}
});
}
public void Process(View view) {
String id_book = this.id_book.toString().trim();
String startdate = this.startdate.getText().toString().trim();
String enddate = this.enddate.getText().toString().trim();
ProcessNow();
}
private void ProcessNow() {
final ProgressDialog dialog = new ProgressDialog(this);
dialog.setMessage("Please wait.....");
dialog.show();
Call<Book> call = apiInterface.getbooklist(id_book.toString(), startdate.getText().toString(), enddate.getText().toString());
call.enqueue(new Callback<Book>() {
#Override
public void onResponse(Call<Book> call, Response<Book> response) {
String result = response.body().getStatus();
if(result.equals("true"))
{
Intent intent = new Intent(activity_book.this, listbook.class);
startActivity(intent);
}
else if(result.equals("false"))
{
Toast.makeText(activity_book.this, "Load Data Failed", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
}
#Override
public void onFailure(Call<Book> call, Throwable t) {
}
});
}
}
the result should be like in below with json output
{
"status": true,
"id_book": "KD-BKK-2",
"book_name": "ASP.NET MVC",
"author": "Gramed",
"description": "Programming Book",
"book_price": "9000.00",
"id_publication": "KD-PCT-1",
"id_branch": "KD-BRH-1",
"qty": "200",
"rental_qty": "0",
"imagename": "aspmvc.jpg",
"imagepath": "D:\\Jovita S\\file ASP.NET (C# and VB)\\Library\\Library\\Books\\aspmvc.jpg",
"entry_date": "2020-12-31 10:48:16.000"
}
Is something wrong with this code? the list view should be showing on listbook.class but the loading not showing any result (stuck). Any suggestion for this? thank you

how to pass array list data from one dialog fragment to another dialog fragment?

After a long search on the internet I couldn't find any solution to meet my requirements.
I have one array list which is passed into the dialog fragment, but my requirement is:
When the user selects the date it calls the web service again and gets another data according to data and passes the same dialog fragment. How can I achieve that ? I have tried with static value but its not clearing the value. My code is:
public static class DatePickerDialogFragment extends DialogFragment implements
DatePickerDialog.OnDateSetListener
{
String userName;
public interface UserUserIdListener {
void updateIdUserName(String userName);
}
public static final int FLAG_START_DATE = 0;
public static final int FLAG_END_DATE = 1;
public static List<Orederlist>reportorderIdList=new ArrayList<>();
// private List<Userlist> reportUserList = new ArrayList<>();
private int flag = 0;
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void setFlag(int i) {
flag = i;
}
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar calendar = Calendar.getInstance();
Calendar calendar1=Calendar.getInstance();
calendar1.set(year, monthOfYear, dayOfMonth);
calendar.set(year, monthOfYear, dayOfMonth);
String reportOrderIds="";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
if (flag == FLAG_START_DATE) {
textviewFromDate.setText(format.format(calendar.getTime()));
fromDateReport=textviewFromDate.getText().toString();
JSONObject pieObject = new JSONObject();
try
{
pieObject.put("fromDate",""+fromDateReport);
pieObject.put("orderId",""+reportOrderIds);
pieObject.put("password",""+sPrefs.getString(Constants.PASSWORD,""));
pieObject.put("toDate",""+toDateReport);
pieObject.put("user",""+sPrefs.getString(Constants.USER_NAME,""));
pieObject.put("subUser",""+reportSubUsers);
progressDialog = new ProgressDialog(getContext());
progressDialog.setMessage("Loading....");
progressDialog.setCancelable(false);
progressDialog.show();
} catch (Exception e)
{
e.printStackTrace();
}
// String TAG = "delivered";
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
JsonObjectRequest jsOnbjRequest = new
JsonObjectRequest(Request.Method.POST,
Constants.GetSummarizedReports, pieObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response)
{
progressDialog.dismiss();
try {
JSONArray jsonArray = (JSONArray) response.get("orderlist");
{
if (jsonArray.length()>0)
{
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
// Integer name = json.optInt();
String name = json.optString("orderId").toString();
Orederlist user = new Orederlist(name);
user.setOrderId(name);
reportorderIdList.add(user);
}}
}
} catch (Exception e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
}
}) {
#Override
public String getBodyContentType() {
return "application/json";
}
};
jsOnbjRequest.setRetryPolicy(new DefaultRetryPolicy(500000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(jsOnbjRequest);
} else if (flag == FLAG_END_DATE) {
textviewToDate.setText(format.format( calendar1.getTime()));
toDateReport= textviewToDate.getText().toString();
JSONObject pieObject = new JSONObject();
try
{
pieObject.put("fromDate",""+fromDateReport);
pieObject.put("orderId",""+reportOrderIds);
pieObject.put("password",""+sPrefs.getString(Constants.PASSWORD,""));
pieObject.put("toDate",""+toDateReport);
pieObject.put("user",""+sPrefs.getString(Constants.USER_NAME,""));
pieObject.put("subUser",""+reportSubUsers);
progressDialog = new ProgressDialog(getContext());
progressDialog.setMessage("Loading....");
progressDialog.setCancelable(false);
progressDialog.show();
} catch (Exception e)
{
e.printStackTrace();
}
// String TAG = "delivered";
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
JsonObjectRequest jsOnbjRequest = new
JsonObjectRequest(Request.Method.POST,
Constants.GetSummarizedReports, pieObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response)
{
progressDialog.dismiss();
try {
JSONArray jsonArray = (JSONArray) response.get("orderlist");
{
if (jsonArray.length()>0)
{
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
// Integer name = json.optInt();
String name = json.optString("orderId").toString();
Orederlist user = new Orederlist(name);
user.setOrderId(name);
reportorderIdList.add(user);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
}
}) {
#Override
public String getBodyContentType() {
return "application/json";
}
};
jsOnbjRequest.setRetryPolicy(new DefaultRetryPolicy(500000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(jsOnbjRequest);
}
}
}
and for dialog fragment pass data is :
FragmentManager managerOrderIds = getSupportFragmentManager();
UserJobIds dialogOrderIds = new UserJobIds();
dialogOrderIds.setdata(orderIdList,reportorderIdList);//with static array list which is not claer the value
dialogOrderIds.show(managerOrderIds, "Dialog");
What you can do is just create a newInstance of Dialog Fragment assign data to it, then call show().Below is an example.
public class D2Fragment extends DialogFragment {
private ArrayList<String> list;
public static D2Fragment getInstanceFor(ArrayList<String> list){
D2Fragment d2Fragment=new D2Fragment();
d2Fragment.list=list;
return d2Fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.item_dialog, container,
false);
getDialog().setTitle("DialogFragment Sample");
Log.e("size",list.size()+"");// Here is the list
// Do something else
return rootView;
}
}
When you show dialog.
ArrayList<String> list=new ArrayList<>();
list.add("Val1");
list.add("Val2");
D2Fragment d2Fragment=D2Fragment.getInstanceFor(list);
d2Fragment.show(getSupportFragmentManager(),"dialog2");
Or just create a setter for your data.
public class D2Fragment extends DialogFragment {
private ArrayList<String> list;
public void setData(ArrayList<String> list){
this.list=list;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.item_dialog, container,
false);
getDialog().setTitle("DialogFragment Sample");
Log.e("size",list.size()+"");// Here is the list
// Do something else
return rootView;
}
}
and to show Dialog.
ArrayList<String> list = new ArrayList<>();
list.add("Val1");
list.add("Val2");
D2Fragment d2Fragment = new D2Fragment();
d2Fragment.setData(list);
d2Fragment.show(getSupportFragmentManager(), "dialog2");
In activity you can always find that particular DialgFragment by tag you assigned at the time of transaction.
Fragment fragment=getSupportFragmentManager().findFragmentByTag("dialog2");
if(fragment!=null && fragment instanceof D2Fragment){
((D2Fragment)fragment).call();// You can call any public method of this dialog fragment here
}

Filter the ListView Items without use of Button

I am able to Apply Filter to the ListView on the Data through WEB only when i Click on the Search Button. But i Want the data to be filtered when both EditText are filled without clicking on the Search button. I am using two editText: startdate and endDate. when i click on the search button, filter is working but i want the data to be filtered irrespective of the order of entering the date in the editText.
AttendanceStudentFragment
public class AttendanceStudentFragment extends Fragment {
ListView listView;
String Navigation_URL = "http://192.168.100.5:84/api/academics/attendance";
String Navigation_URL_FILTER = "http://192.168.100.5:84/api/academics/searchAttndByDate";
String master_id, date, status, remarks;
EditText editTextStartDate, editTextEndDate;
Button buttonSearch;
Calendar myCalendar = Calendar.getInstance();
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.student_attendance_listview, container, false);
setHasOptionsMenu(true);
SessionManagement sessionManagement = new SessionManagement(getContext());
master_id = sessionManagement.getMasterId();
listView = (ListView) view.findViewById(R.id.list_student_attendance);
editTextStartDate = (EditText) view.findViewById(R.id.student_attendance_startDate);
editTextEndDate = (EditText) view.findViewById(R.id.student_attendance_endDate);
buttonSearch = (Button) view.findViewById(R.id.student_attendance_searchbutton);
// editTextStartDate.setInputType(InputType.TYPE_NULL);
// editTextStartDate.requestFocus();
final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, month);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateLabelStartDate();
}
};
final DatePickerDialog.OnDateSetListener date1 = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, month);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateLabelEndDate();
}
};
editTextStartDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new DatePickerDialog(getContext(), date, myCalendar
.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
});
// collegeAdmissionStartDatePicker.show();
editTextEndDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new DatePickerDialog(getContext(), date1, myCalendar
.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
});
getAttendanceData();
buttonSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getAttendanceDataWithFilter();
}
});
if(editTextEndDate.length()!=0 && editTextStartDate.length()!=0){
getAttendanceDataWithFilter();
}
return view;
}
private void updateLabelStartDate() {
String myFormat = "MM/dd/yy"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
editTextStartDate.setText(sdf.format(myCalendar.getTime()));
//editTextEndDate.setText(sdf.format(myCalendar.getTime()));
}
private void updateLabelEndDate() {
String myFormat = "MM/dd/yy"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
// editTextStartDate.setText(sdf.format(myCalendar.getTime()));
editTextEndDate.setText(sdf.format(myCalendar.getTime()));
}
public void getAttendanceData() {
String URL = Navigation_URL + "?StdID=" + master_id;
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
ArrayList<StudentAttendancePojo> student_attendance_list = new ArrayList<>();
System.out.println(student_attendance_list.size());
JSONArray jArray = new JSONArray(response);
// studentFeeInformation = new StudentFeeInformation(response);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonObject = jArray.getJSONObject(i);
date = jsonObject.getString("DateOfAttendance").substring(0, 10);
status = jsonObject.getString("STATUS");
remarks = jsonObject.getString("Remarks");
// student_list.add(new StudentFeeInformation(status, DateofReceiptIssued, ReceiptNumber, FeeReceivedDate));
//
//JSONArray jArray1 = jsonObject.getJSONArray("Description");
StudentAttendancePojo studentAttendancePojo = new StudentAttendancePojo(date, status, remarks);
System.out.println("total lengthArray" + jArray.length());
student_attendance_list.add(studentAttendancePojo);
}
System.out.println("student_list size:" + student_attendance_list.size());
StudentAttendanceAdapter studentAttendanceAdapter = new StudentAttendanceAdapter(getActivity(), student_attendance_list);
System.out.println(student_attendance_list.size());
listView.setAdapter(studentAttendanceAdapter);
} catch (JSONException e) {
System.out.println("This is not good");
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Toast.makeText(view.Fee.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
return headers;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
requestQueue.add(stringRequest);
}
public void getAttendanceDataWithFilter() {
// editTextStartDate.getText().toString();
// editTextEndDate.getText().toString();
// String URL = Navigation_URL_FILTER + "?StdID=" + master_id + "&fromDate=" + "2017-06-01" + "&toDate=" + "2017-06-10";
String URL = Navigation_URL_FILTER + "?StdID=" + master_id + "&fromDate=" + editTextStartDate.getText() + "&toDate=" + editTextEndDate.getText();
//String URL = Navigation_URL + "?fromDate=" + editTextStartDate + "&toDate" + editTextEndDate + "StdID" + master_id;
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
ArrayList<StudentAttendancePojo> student_attendance_list = new ArrayList<>();
System.out.println(student_attendance_list.size());
JSONArray jArray = new JSONArray(response);
// studentFeeInformation = new StudentFeeInformation(response);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonObject = jArray.getJSONObject(i);
date = jsonObject.getString("DateOfAttendance").substring(0, 10);
status = jsonObject.getString("STATUS");
remarks = jsonObject.getString("Remarks");
// student_list.add(new StudentFeeInformation(status, DateofReceiptIssued, ReceiptNumber, FeeReceivedDate));
//
//JSONArray jArray1 = jsonObject.getJSONArray("Description");
StudentAttendancePojo studentAttendancePojo = new StudentAttendancePojo(date, status, remarks);
System.out.println("total lengthArray" + jArray.length());
student_attendance_list.add(studentAttendancePojo);
}
System.out.println("student_list size:" + student_attendance_list.size());
StudentAttendanceAdapter studentAttendanceAdapter = new StudentAttendanceAdapter(getActivity(), student_attendance_list);
System.out.println(student_attendance_list.size());
listView.setAdapter(studentAttendanceAdapter);
} catch (JSONException e) {
System.out.println("This is not good");
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Toast.makeText(view.Fee.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
return headers;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
requestQueue.add(stringRequest);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.dashboard, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle item selection
switch (item.getItemId()) {
case R.id.action_settings:
// do s.th.
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
How can this issue be Solved?
Try this just add your edittext's addTextChangedListener it may help you..
editTextEndDate.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
if(editTextStartDate.getText.toString() != ""){
getAttendanceDataWithFilter();
}
}
});
One:Use a listener like OnFocusChangeListener,when the Edittext lose focus you can refresh date!
Two:Add a TextWatcher on Edittext,when text changed,check it and update date!

Categories

Resources