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();
}
});
}
}
Related
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
Hi in the below on back press from one fragment to current fragement duplicate list got creating using recyclerview in android.
If I am load my fragment it is giving me correct response.but moving to next fragment and coming back to current fragment .when I am coming back to the current fragment it is showing duplicate list in and not closing app.
public class HomeFragment extends Fragment implements ViewAppointmentAdapter.SelectIemClickListner,ViewAppointmentAdapter.StartSelectIemClickListner,DoctorAdapter.SelectIemClickListner, SpeclializationAdapter.MyItemClickListener, PatientAdapter.SelectIemClickListner,DoctorPatientListAdapter.SelectIemClickListner,DoctorPatientListAdapter.StartSelectIemClickListner,ViewAppointmentAdapter.SelectIemCancelClickListner {
public HomeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
((NavigationViewActivity) getActivity()).setActionBarTitle("Home");
View rootView = inflater.inflate(R.layout.activity_home, container, false);
data_viewpatientlists = new ArrayList<>();
viewpatientdataLists = new ArrayList<>();
recyclerAppointmentlist = rootView.findViewById(R.id.recyclerAppointmentlist);
recyclerAppointmentlist.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
viewAppointmentAdapter = new ViewAppointmentAdapter(requireContext(), data_viewpatientlists, this, this, this);
data_viewpatientlists.clear();
viewPatientList();
}
private void viewPatientList() {
// progressDialog = new ProgressDialog(getContext());
// progressDialog.setIndeterminate(true);
// progressDialog.setMessage("Loading...");
// progressDialog.setCanceledOnTouchOutside(false);
// progressDialog.setCancelable(false);
// progressDialog.show();
String RegistrationNo = LoginId;
final APIService service = RetroClass.getRetrofitInstance().create(APIService.class);
Call<Patient_ViewPatientlist> call = service.ViewPatientList(RegistrationNo);
Log.wtf("URL Called", call.request().url() + "");
call.enqueue(new Callback<Patient_ViewPatientlist>() {
#Override
public void onResponse(Call<Patient_ViewPatientlist> call, Response<Patient_ViewPatientlist> response) {
Log.e("response", new Gson().toJson(response.body()));
if (response.isSuccessful()) {
Log.e("response", new Gson().toJson(response.body()));
Patient_ViewPatientlist patient_patientlist = response.body();
viewpatientdataLists = patient_patientlist.getData();
for (Data_Viewpatientlist view_patientList : viewpatientdataLists) {
String First_name = view_patientList.getFName();
String last_name = view_patientList.getLName();
String SlotFrom = view_patientList.getSlotFrom();
String SlotTo = view_patientList.getSlotTo();
String FromDate = view_patientList.getForDate();
String booking_id = view_patientList.getBookingId();
String doct_id = view_patientList.getDocId();
String profile_photo = view_patientList.getProfllePhoto();
DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd");
DateFormat outputFormat = new SimpleDateFormat("dd-MMM-yyyy");
Date date = null;
try {
date = inputFormat.parse(FromDate);
} catch (ParseException e) {
e.printStackTrace();
}
String outputDateStr = outputFormat.format(date);
Data_Viewpatientlist data_doctorpatientlist = new Data_Viewpatientlist(booking_id, First_name, last_name, outputDateStr, SlotFrom, SlotTo);
data_viewpatientlists.add(data_doctorpatientlist);
Log.d("data_viewpatientlists", String.valueOf(data_viewpatientlists.size()));
recyclerAppointmentlist.setAdapter(viewAppointmentAdapter);
viewAppointmentAdapter.notifyDataSetChanged();
}
}
// progressDialog.dismiss();
}
#Override
public void onFailure(Call<Patient_ViewPatientlist> call, Throwable t) {
Log.d("error", t.getMessage());
// progressDialog.dismiss();
}
});
}
I haven't looked deeply, but it looks like you are clearing the list of the passed adapter only when you create your fragment.
When you return to the previous fragment, the onCreateView is not called, it is called fragment method onAttach.
Try to override the onAttach method and clear the list there.
Try This:
first of all clear a data of 'recyclerAppointmentlist' in onResponse() and then add the new records
it looks like this:
call.enqueue(new Callback<Patient_ViewPatientlist>() {
#Override
public void onResponse(Call<Patient_ViewPatientlist> call, Response<Patient_ViewPatientlist> response) {
Log.e("response", new Gson().toJson(response.body()));
if (response.isSuccessful()) {
viewpatientdataLists.clear()
Patient_ViewPatientlist patient_patientlist = response.body();
viewpatientdataLists = patient_patientlist.getData();
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);
This question already has an answer here:
getContactsFromFirebase() method return an empty list
(1 answer)
Closed 4 years ago.
public class ShowBPGraphActivity extends AppCompatActivity {
public GraphView graphView;
public LineGraphSeries <DataPoint>lineGraphSeries;
public String systolicbp;
public String diastolicbp;
public String timebp;
public String datebp;
public DatabaseReference db;
public BPFragmentTable bpFragmentTable = new BPFragmentTable( );
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_show_bp_graph );
ButterKnife.bind( this );
db = FirebaseDatabase.getInstance().getReference("bpfragmentTable");
final GraphView graph = (GraphView) findViewById( R.id.graphView );
final List<BPFragmentTable> bpFragmentTableList = new ArrayList<>();
//Get datasnapshot at your "users" root node
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("bpfragmentTable");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<BPFragmentTable> bpfragmentTableList = new ArrayList<>();
for(DataSnapshot dataSnapshot1 :dataSnapshot.getChildren()){
BPFragmentTable bpfragmentTable = dataSnapshot1.getValue(BPFragmentTable.class);
systolic = bpfragmentTable.getSystolicbp();
diastolic = bpfragmentTable.getDiastolicbp();
date = bpfragmentTable.getDatebp();
time = bpfragmentTable.getTimebp();
//bpfragmentTable.setSystolicbp(systolic);
//bpfragmentTable.setDiastolicbp(diastolic);
//bpfragmentTable.setDatebp(date);
//bpfragmentTable.setTimebp(time);
bpfragmentTableList.add(bpfragmentTable);
// Toast.makeText(MainActivity.this,""+name,Toast.LENGTH_LONG).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
//handle databaseError
}
});
// please help me why i get null value in systolic diastolic date and time
System.out.println( "systolicbp" + systolicbp );
System.out.println( "diastolicbp" + diastolicbp );
System.out.println( "datebp" + datebp );
System.out.println( "timebp" + timebp );
try {
#SuppressLint("SimpleDateFormat") SimpleDateFormat formatter = new SimpleDateFormat("hh:mm a\nMMM dd yyyy");
dateValued = formatter.parse(datebp);
dateInMills = dateValued.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
final long xlong = dateInMills;
final int ysystolicInt = Integer.parseInt( systolicbp );
final int ydiastolicInt = Integer.parseInt( diastolicbp );
this is the error in the picture
I want to get bpfragmentTable all values and store all values in the string variable and use that variable to draw a graph in the graph view. I want to get all values from the table-BPFragment table in the picture:
and this is the class of getter and setter of BPFragmentTable.class
public class BPFragmentTable {
public String bpid;
public String systolicbp;
public String diastolicbp;
public String datebp;
public String timebp;
public BPFragmentTable(){}
public BPFragmentTable(String bpid,String systolicbp,String diastolicbp,String datebp,String timebp) {
this.bpid = bpid;
this.systolicbp = systolicbp;
this.diastolicbp = diastolicbp;
this.datebp = datebp;
this.timebp = timebp;
}
public String getBpid() {
return bpid;
}
public void setBpid(String bpid) {
this.bpid = bpid;
}
public String getSystolicbp() {
return systolicbp;
}
public void setSystolicbp(String systolicbp) {
this.systolicbp = systolicbp;
}
public String getDiastolicbp() {
return diastolicbp;
}
public void setDiastolicbp(String diastolicbp) {
this.diastolicbp= diastolicbp;
}
public String getDatebp() {
return datebp;
}
public void setDatebp(String datebp) {
this.datebp= datebp;
}
public String getTimebp() {
return timebp;
}
public void setTimebp(String timebp) {
this.timebp= timebp;
}
}
Why do I get null object reference?
Data is loaded from Firebase asynchronously. By the time you call formatter.parse(datebp) the onDataChange method hasn't run yet, and datebp hasn't been set. You will need to move the parsing of the data into onDataChange:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("bpfragmentTable");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<BPFragmentTable> bpfragmentTableList = new ArrayList<>();
for(DataSnapshot dataSnapshot1 :dataSnapshot.getChildren()){
BPFragmentTable bpfragmentTable = dataSnapshot1.getValue(BPFragmentTable.class);
systolic = bpfragmentTable.getSystolicbp();
diastolic = bpfragmentTable.getDiastolicbp();
date = bpfragmentTable.getDatebp();
time = bpfragmentTable.getTimebp();
bpfragmentTableList.add(bpfragmentTable);
System.out.println( "systolicbp" + systolicbp );
System.out.println( "diastolicbp" + diastolicbp );
System.out.println( "datebp" + datebp );
System.out.println( "timebp" + timebp );
try {
#SuppressLint("SimpleDateFormat") SimpleDateFormat formatter = new SimpleDateFormat("hh:mm a\nMMM dd yyyy");
dateValued = formatter.parse(datebp);
dateInMills = dateValued.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});
This asynchronous nature is a common pitfall for developers new to Firebase. Since asynchronous APIs are extremely common in modern programming, I highly recommend you learn about them quickly. For some good introductory material, see:
getContactsFromFirebase() method return an empty list (which also shows how to use an interface to get the values out of onDataChange)
this blog post on asynchronous APIs
Setting Singleton property value in Firebase Listener (where I explained how in some cases you can get synchronous data loading, but usually can't)
I have a listview that gets layout from adapter. The value was fetch using retrofit 2 and parse on the listview. This value updates on the API and want to implement the same feature. The problem is that it doubles value when runnable process. How can I make it work?
Here is the code:
class VehicleListFragment extends Fragment {
private ProgressDialog pDialog;
private ListView lv;
ListAdapter adapter;
final Handler handler = new Handler();
public static String baseUrl = "http://mark.journeytech.com.ph/mobile_api/";
public static NetworkAPI networkAPI;
public ArrayList<HashMap<String, String>> vehicle = new ArrayList<>();
String a = "";
ArrayList pna;
public interface NetworkAPI {
#POST("vehicle_details.php")
#Headers({"Content-Type:application/json; charset=UTF-8"})
Call<JsonElement> loginRequest(#Body VehicleRequestPojo body);
}
public static class VehicleRequestPojo {
String ucsi_num;
String client_table;
String markutype;
public VehicleRequestPojo(String ucsi_num, String client_table, String markutype) {
this.ucsi_num = ucsi_num;
this.client_table = client_table;
this.markutype = markutype;
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
searchItem.setVisible(false);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MainActivity csActivity;
csActivity = (MainActivity) getActivity();
csActivity.getSupportActionBar().setTitle("Vehicle List");
Runnable refresh = new Runnable() {
#Override
public void run() {
new GetVehicles().execute();
handler.postDelayed(this, 60 * 1000);
}
};
handler.postDelayed(refresh, 60 * 1000);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_vehicle, container, false);
lv = (ListView) v.findViewById(R.id.list);
new GetVehicles().execute();
return v;
}
private class GetVehicles extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
/* // Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();*/
}
#Override
protected Void doInBackground(Void... arg0) {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(logging);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient.build())
.build();
networkAPI = retrofit.create(NetworkAPI.class);
VehicleRequestPojo loginRequest = new VehicleRequestPojo(MainActivity.ucsi_num, client_table, markutype);
Call<JsonElement> call = networkAPI.loginRequest(loginRequest);
call.enqueue(new Callback<JsonElement>() {
#Override
public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
// success response
if (response.body().isJsonArray()) {
JsonArray objectWhichYouNeed = response.body().getAsJsonArray();
System.out.println(objectWhichYouNeed);
for (int i = 0; i < response.body().getAsJsonArray().size(); i++) {
JsonElement je = response.body().getAsJsonArray().get(i);
JsonObject jo = je.getAsJsonObject();
String plate_n = jo.get("plate_num").toString();
String plate_nString = plate_n;
plate_nString = plate_nString.replace("\"", "");
String plate_num = String.valueOf(plate_nString);
String gps_n = jo.get("gps_num").toString();
String gps_nString = gps_n;
gps_nString = gps_nString.replace("\"", "");
String gps_num = String.valueOf(gps_nString);
String locat = jo.get("location").toString();
String locatString = locat;
locatString = locatString.replace("\"", "");
String location = String.valueOf(locatString);
String da = jo.get("date").toString();
String daString = da;
daString = daString.replace("\"", "");
String date = String.valueOf(daString);
String ti = jo.get("time").toString();
String tiString = ti;
tiString = tiString.replace("\"", "");
String time = String.valueOf(tiString);
String lati = jo.get("lat").toString();
String latiString = lati;
latiString = latiString.replace("\"", "");
String lat = String.valueOf(latiString);
String longi = jo.get("lng").toString();
String longiString = longi;
longiString = longiString.replace("\"", "");
String lng = String.valueOf(longiString);
String en = jo.get("engine").toString();
String enString = en;
enString = enString.replace("\"", "");
String engine = String.valueOf(enString);
String re = jo.get("remarks").toString();
String reString = re;
reString = reString.replace("\"", "");
String remarks = String.valueOf(reString);
if (lat != null && !lat.equals("null") || (lng != null && !lng.equals("null"))) {
// tmp hash map for detail [single]
HashMap<String, String> details = new HashMap<>();
// adding each child node to HashMap key => value
details.put("plate_num", plate_num);
details.put("gps_num", gps_num);
details.put("location", location);
details.put("date", date);
details.put("time", time);
details.put("lat", lat);
details.put("lng", lng);
details.put("engine", engine);
details.put("remarks", remarks);
a = details.get("date");
// adding vehicle to vehicle list
vehicle.add(details);
/**
* Updating parsed JSON data into ListView
* */
adapter = new SimpleAdapter(getActivity(), vehicle,
R.layout.list_vehicle, new String[]{"plate_num",
"location", "date", "time", "lat", "lng", "engine",
"remarks"},
new int[]{R.id.plate_num, R.id.location, R.id.date, R.id.time, R.id.latitude, R.id.longitude,
R.id.engine, R.id.remarks});
lv.setAdapter(null);
lv.setAdapter(adapter);
// ((BaseAdapter) lv.getAdapter()).notifyDataSetChanged();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View v, int position, long l) {
TextView plate_n = (TextView) v.findViewById(R.id.plate_num);
TextView dat = (TextView) v.findViewById(R.id.date);
TextView tim = (TextView) v.findViewById(R.id.time);
TextView loc = (TextView) v.findViewById(R.id.location);
TextView lat = (TextView) v.findViewById(R.id.latitude);
TextView lng = (TextView) v.findViewById(R.id.longitude);
TextView eng = (TextView) v.findViewById(R.id.engine);
TextView rem = (TextView) v.findViewById(R.id.remarks);
String plate_num = plate_n.getText().toString();
String date = dat.getText().toString();
String time = tim.getText().toString();
String location = loc.getText().toString();
String latitude = lat.getText().toString();
String longitude = lng.getText().toString();
String engine = eng.getText().toString();
String remarks = rem.getText().toString();
Bundle bundle = new Bundle();
bundle.putString("plate_num", plate_num);
bundle.putString("date", date);
bundle.putString("time", time);
bundle.putString("location", location);
bundle.putString("latitude", latitude);
bundle.putString("longitude", longitude);
bundle.putString("engine", engine);
bundle.putString("remarks", remarks);
if((!latitude.equals("") && latitude != null) || (!longitude.equals("") && longitude != null) )
{
Fragment mFragment = new VehicleListMapFragment(getActivity(), getActivity());
getFragmentManager().beginTransaction().addToBackStack("sd").replace(R.id.mainLayout, mFragment).commit();
mFragment.setArguments(bundle);
} else {
Toast.makeText(getContext(), "Invalid Data.", Toast.LENGTH_LONG).show();
}
}
});
}
}
} else {
System.out.println("Not a JSONArray.");
}
}
#Override
public void onFailure(Call<JsonElement> call, Throwable t) {
// failure response
System.out.println(call.toString());
}
});
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
/* // Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();*/
}
}
}
Also could it be possible to use lv.invalidateViews();
lv.refreshDrawableState(); also could it be a .clear()? and refetch the api?
Try using this:
Runnable refresh = new Runnable() {
#Override
public void run() {
vehicle.clear(); // This will clear the old data from arraylist.
new GetVehicles().execute();
handler.postDelayed(this, 60 * 1000); //This will call after every 60 seconds.
}
};
handler.postDelayed(refresh, 60 * 1000); // This will be call only first time when the code is executed.
Also remove private from private ProgressDialog pDialog; so that it can be accessed by from another class GetVehicles.
Suggestion : Use RecylerView in place of listview
Hope this helps.
Declare your adapter, list variable in global. The idea is something like this
//Global
private ListView lv;
private ListAdapter adapter;
private ArrayList<HashMap<String, String>> vehicle;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_vehicle, container, false);
lv = (ListView) v.findViewById(R.id.list);
vehicle = new ArrayList<>();
adapter = new SimpleAdapter(getContext(), vehicle,
R.layout.list_vehicle, new String[]{"plate_num",
"location", "date", "time", "lat", "lng", "engine",
"remarks",},
new int[]{R.id.plate_num, R.id.location, R.id.date, R.id.time, R.id.latitude, R.id.longitude,
R.id.engine, R.id.remarks});
new GetVehicles().execute();
return v;
}
//right after you get the new dataset from **GetVehicles** ,
//update vehicle list and call,
((BaseAdapter) lv.getAdapter()).notifyDataSetChanged();