I need to format date and time in the RemoteViewsFactory class. I know how to use DateFormat/SimpleDate Format. I'm doing it like in the thread below but the app keeps stopping when pressing on the widget on a physical device: remoteViews.setTextViewText(R.id.tvTaskDay, DateFormat.getDateInstance().format(task.getDay()));
Android - ListView items inside app widget not selectable
I'm also formatting in the parent activity and it works. Is it possible to reference the SimpleDateFormat code from there? Thank you in advance.
P.S. Error message.
My RemoteViewsFactory class:
public class ScheduleWidgetViewFactory implements RemoteViewsService.RemoteViewsFactory
{
private ArrayList<Schedule> mScheduleList;
private Context mContext;
public ScheduleWidgetViewFactory(Context context)
{
mContext = context;
}
#Override
public void onCreate()
{
}
#Override
public void onDataSetChanged()
{
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(mContext);
Gson gson = new Gson();
Type type = new TypeToken<List<Schedule>>() {}.getType();
String gsonString = sharedPreferences.getString("ScheduleList_Widget", "");
mScheduleList = gson.fromJson(gsonString, type);
}
#Override
public int getCount()
{
return mScheduleList.size();
}
#Override
public RemoteViews getViewAt(int position)
{
Schedule schedule = mScheduleList.get(position);
RemoteViews itemView = new RemoteViews(mContext.getPackageName(), R.layout.schedule_widget_list_item);
itemView.setTextViewText(R.id.schedule_widget_station_name, schedule.getStationScheduleName());
itemView.setTextViewText(R.id.schedule_widget_arrival, DateFormat.getDateInstance().format(schedule.getExpectedArrival()));
itemView.setTextViewText(R.id.schedule_widget_towards, schedule.getDirectionTowards());
Intent intent = new Intent();
intent.putExtra(ScheduleWidgetProvider.EXTRA_ITEM, schedule);
itemView.setOnClickFillInIntent(R.id.schedule_widget_list, intent);
return itemView;
}
#Override
public int getViewTypeCount()
{
return 1;
}
Parent Activity:
#Override
public void returnScheduleData(ArrayList<Schedule> simpleJsonScheduleData)
{
if (simpleJsonScheduleData.size() > 0)
{
scheduleAdapter = new ScheduleAdapter(simpleJsonScheduleData, StationScheduleActivity.this);
scheduleArrayList = simpleJsonScheduleData;
mScheduleRecyclerView.setAdapter(scheduleAdapter);
scheduleAdapter.setScheduleList(scheduleArrayList);
stationArrival = scheduleArrayList.get(0);
stationShareStationName = stationArrival.getStationScheduleName();
stationShareArrivalTime = stationArrival.getExpectedArrival();
stationShareDirection = stationArrival.getDirectionTowards();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
Date date = null;
try {
date = simpleDateFormat.parse(stationArrival.getExpectedArrival());
date.toString();
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat newDateFormat = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss");
String finalDate = newDateFormat.format(date);
stationShareArrivalTime = finalDate;
//Store Schedule Info in SharedPreferences
SharedPreferences appSharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor prefsEditor = appSharedPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(scheduleArrayList);
prefsEditor.putString("ScheduleList_Widget", json);
prefsEditor.apply();
}
else
{
emptySchedule.setVisibility(View.VISIBLE);
}
In case anyone else has is stuck on this. As Mike M. pointed out in the comments, the DateFormat code structure in RemoteViewsFactory is the same as everywhere else.
private String stationWidgetArrivalTime;
#Override
public RemoteViews getViewAt(int position)
{
Schedule schedule = mScheduleList.get(position);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
Date date = null;
try {
date = simpleDateFormat.parse(schedule.getExpectedArrival());
date.toString();
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat newDateFormat = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss");
String finalDate = newDateFormat.format(date);
stationWidgetArrivalTime = finalDate;
RemoteViews itemView = new RemoteViews(mContext.getPackageName(), R.layout.schedule_widget_list_item);
itemView.setTextViewText(R.id.schedule_widget_station_name, schedule.getStationScheduleName());
itemView.setTextViewText(R.id.schedule_widget_arrival, stationWidgetArrivalTime);
itemView.setTextViewText(R.id.schedule_widget_towards, schedule.getDirectionTowards());
Intent intent = new Intent();
intent.putExtra(ScheduleWidgetProvider.EXTRA_ITEM, schedule);
itemView.setOnClickFillInIntent(R.id.schedule_widget_list, intent);
return itemView;
}
Related
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();
}
});
}
}
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);
I have two datepickers in my activity.
I want startdate of datePickerB dialog to be updated automatically based on date selected in datePickerA dialog.
I use setMinDate for datePickerB. setMinDate works fine for the very first time. But couldn't update or reset the mindate of datePickerB for consecutive updates in datePickerA. Kindly help.
Searched for all possible solutions but of no use. Kindly help
Below is my code. The code used in oncreate gets executed , but further setMinDate function called in HandleResponse ( this is the function that gets called once datepickerA is set )
//On OnCreate
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_YEAR, 1);
Date tomorrow = calendar.getTime();
long t = tomorrow.getTime();
fromDatePicker.getDatePicker().setMinDate(t);
//
toDatePicker.getDatePicker().setMinDate(t);
public void HandleResponse(Response response)
{
String sqlRes = "";
try {
String sResJson = response.body().string();
JSONObject jReader = new JSONObject(sResJson);
JSONObject jRes = jReader.getJSONObject("Result");
sqlRes = jRes.getString("res");
final int sqlMilkQty = jRes.getInt("qty");
String enddate = jRes.getString("date");
Date d = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
d = sdf.parse(enddate);
} catch (ParseException e) {
e.printStackTrace();
}
if (d != null && fromDate!= null) {
long t = d.getTime();
long t1 = fromDate.getTime();
toDatePicker.getDatePicker().setMinDate(t1);
toDatePicker.getDatePicker().setMaxDate(t);
}
Handler mainHandler = new Handler(Looper.getMainLooper());
if (sqlRes.equals("PASS"))
{
mainHandler.post(new Runnable() {
#Override
public void run() {
milkQuantity = sqlMilkQty;
txtMilkQuantity.setText(String.valueOf(milkQuantity));
}
});
}
else {
}
} catch (IOException e) {
DisplayError();
}
catch (JSONException e) {
DisplayError();
}
}
I check a webside if new items have been posted and if yes a string value "new" is added to these items.
Now the long value "date" always stays on -1, as a result the string value "new" is added after every item, also for items added for example yesterday.
"new" should not be shown for values older then today, please help.
Thank you.
public class TopicView extends LinearLayout implements LoadTopicImageCallback {
private LoadTopicImageTask topicImageTask = null;
private boolean newItem = false;
private long date = -1;
public TopicView(final Context context, final Topic topic) {
super(context);
init(topic);
}
public TopicView(final Context context, final Topic topic, final String suffix) {
super(context);
init(topic);
final long latest = new Settings(context).getLatest(suffix);
try {
final Date d = Util.parseDate(topic.getTime());
date = d.getTime();
} catch (final ParseException e) {
}
//String new gets added//
if (latest == -1 || date > latest) {
findViewById(R.id.topic_view_new).setVisibility(View.VISIBLE);
newItem = true;
}
}
public boolean isNewItem() {
return newItem;
}
public long getDate() {
return date;
}
EDIT:
public static String formatDate(final long dt) {
return formatDate(new Date(dt));
}
public static String formatDate(final Date date) {
final DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
return df.format(date);
}
public static final Date parseDate(final String date) throws ParseException {
final String pattern = "EEE MMM dd, yyyy h:mm a";
return parseDate(date, pattern);
}
public static final Date parseDate(final String date, final String pattern)
throws ParseException {
final SimpleDateFormat format = new SimpleDateFormat(pattern, Locale.US);
return format.parse(date);
}
Unless you're sure that you're calling the second constructor, you never initialise the date here:
public TopicView(final Context context, final Topic topic) {
super(context);
init(topic);
// add some initialisation for "date" here
}
And even if you are, it would've been helpful to see that small part of code too.
As an aside, can I point out that it's fine to consume exceptions, but even a shred of debug output can help you in the long run. Maybe change
try {
final Date d = Util.parseDate(topic.getTime());
date = d.getTime();
} catch (final ParseException e) {
}
to:
try {
final Date d = Util.parseDate(topic.getTime());
date = d.getTime();
} catch (final ParseException e) {
e.printStackTrace(); // Or some log that your define yourself.
}
I have the following code below in the server stored as gmt and would like it to change based on android device timezone.I am getting wrong value unable to figure out the mistake.I really appreciate any help.
Thanks in Advance.
public class MainActivity extends Activity {
TextView t;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String d="2014-01-14 16:28:50";
t=(TextView)findViewById(R.id.textView1);
Timestamp ts = Timestamp.valueOf(d);
long tsTime1 = ts.getTime();
String r=getDate(tsTime1);
t.setText(r);
}
private String getDate(long timeStamp){
SimpleDateFormat objFormatter = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
objFormatter.setTimeZone(TimeZone.getDefault());
Calendar objCalendar =
Calendar.getInstance(TimeZone.getDefault());
objCalendar.setTimeInMillis(timeStamp*1000);//edit
String result = objFormatter.format(objCalendar.getTime());
objCalendar.clear();
return result;
}
}
public String TimeFormating(String Time)
{
SimpleDateFormat format_before = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");
SimpleDateFormat format_to_Convert = new SimpleDateFormat("hh:mm a",Locale.getDefault());
format_before.setTimeZone(TimeZone.getTimeZone("GMT"));
format_to_Convert.setTimeZone(TimeZone.getDefault());
Date time = null;
try
{
time = format_before.parse(Time);
} catch (ParseException e)
{
e.printStackTrace();
}
return format_to_Convert.format(time).toLowerCase(Locale.getDefault());
}