This is the TimePreference class which extends DialogPreference
import android.content.Context;
import android.content.res.TypedArray;
import androidx.preference.DialogPreference;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TimePicker;
public class TimePreference extends DialogPreference {
private int lastHour=0;
private int lastMinute=0;
private TimePicker picker=null;
public static int getHour(String time) {
String[] pieces=time.split(":");
return(Integer.parseInt(pieces[0]));
}
public static int getMinute(String time) {
String[] pieces=time.split(":");
return(Integer.parseInt(pieces[1]));
}
public TimePreference(Context context, AttributeSet attrs) {
super(context, attrs);
setPositiveButtonText("Set");
setNegativeButtonText("Cancel");
}
#Override
protected View onCreateDialogView() {
picker=new TimePicker(getContext());
return(picker);
}
#Override
protected void onBindDialogView(View v) {
super.onBindDialogView(v);
picker.setCurrentHour(lastHour);
picker.setCurrentMinute(lastMinute);
}
#Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (positiveResult) {
lastHour=picker.getCurrentHour();
lastMinute=picker.getCurrentMinute();
String time=String.valueOf(lastHour)+":"+String.valueOf(lastMinute);
if (callChangeListener(time)) {
persistString(time);
}
}
}
#Override
protected Object onGetDefaultValue(TypedArray a, int index) {
return(a.getString(index));
}
#Override
protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
String time;
if (restoreValue) {
if (defaultValue==null) {
time=getPersistedString("00:00");
}
else {
time=getPersistedString(defaultValue.toString());
}
}
else {
time=defaultValue.toString();
}
lastHour=getHour(time);
lastMinute=getMinute(time);
}
}
When I use androidx.preference.DialogPreference, it is showing Cannot resolve methods 'onDialogClosed', 'onBindDialogView' in 'DialogPreference' Also, onSetInitialValue method is showing deprecated. I have used PreferenceFragmentCompat instead of PreferenceFragment
I have seen few solutions where it is told to split the TimePreference class into two classes, but I am not getting how exactly that is to be done and what extra settings are to be done in PreferenceFragmentCompat
Can I get a solution to this with a working example.
Related
I am a newbie at android studio and am trying to make a simple todolist app. I have a daily alarm set up using Alarm Manager but I would like the user to be able to change the timing that this daily alarm goes off in the settings page. Therefore, I need a timepicker in preferencescreen and I have learnt that you can do this using custom DialogPreferences.
I have tried to follow this tutorial http://www.infiniteimprob.com/blog/custom-preferences/ but it shows this exceptioncom.example.todolist.TimePickerPreference cannot be cast to androidx.preference.Preference I have a feeling that this is due to compatibility issues because I used the androidx library for my other imports. I think that this will be solved if I were to import the androidx.preference.DialogPreference instead of android.preference.DialogPreference; Can someone tell me how I can go about this change? I have read this answer Difference between DialogPreference before and after AndroidX but I still do not really know how to execute it.
This is my timepickerpreference class as followed on the website:
import android.content.res.TypedArray;
import android.os.Build;
import android.preference.DialogPreference;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;
import android.widget.TimePicker;
public class TimePickerPreference extends DialogPreference {
private static final int DEFAULT_TIME = 0;
private TimePicker mTimePicker;
private int currentTime;
public TimePickerPreference(Context context, AttributeSet attrs){
super(context, attrs);
setDialogLayoutResource(R.layout.timepickerpreferencelayout);
setPositiveButtonText("ok");
setNegativeButtonText("cancel");
}
private static int getTime(int hour, int minute){
return hour*60*60*1000 + minute*60*1000;
}
private static int getHour(int value){
return (int)(value / (60*60*1000));
}
private static int getMinute(int value){
return (int)(value % (60*60*1000));
}
#Override
protected View onCreateDialogView() {
View view = super.onCreateDialogView();
mTimePicker = (TimePicker) view.findViewById(R.id.timePicker);
mTimePicker.setIs24HourView(true);
if (Build.VERSION.SDK_INT >= 23)
{
mTimePicker.setHour(getHour(currentTime));
mTimePicker.setMinute(getMinute(currentTime));
}
else
{
mTimePicker.setCurrentHour(getHour(currentTime));
mTimePicker.setCurrentMinute(getMinute(currentTime));
}
mTimePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener()
{
#Override
public void onTimeChanged(TimePicker timePicker, int hour, int minute)
{
TimePickerPreference.this.currentTime = getTime(hour, minute);
}
});
TextView messageTextView = (TextView) view.findViewById(R.id.messageTextView);
if (getDialogMessage() == null || getDialogMessage().toString().trim().length() == 0)
messageTextView.setVisibility(View.GONE);
messageTextView.setText(getDialogMessage());
return view;
}
#Override
protected Object onGetDefaultValue(TypedArray a, int index)
{
return a.getInt(index, DEFAULT_TIME);
}
#Override
protected void onSetInitialValue(boolean restorePersistedValue, Object defaultValue)
{
if(restorePersistedValue)
{
currentTime = this.getPersistedInt((int) (defaultValue == null ? DEFAULT_TIME : defaultValue));
}
else
{
currentTime = (int) defaultValue;
if (shouldPersist())
persistInt(currentTime);
}
}
#Override
protected void onDialogClosed(boolean positiveResult)
{
if (positiveResult)
persistInt(currentTime);
}
}
I am actually searching for an android clock view whose time can be set in the activity and then it will start working from that setted time.I saw the TextClock view but it seemed that only the timezone can be set.Can anyone help me?
Use this class, might help you, You can change date time whatever you want
import android.content.Context;
import android.database.ContentObserver;
import android.os.Handler;
import android.os.SystemClock;
import android.provider.Settings;
import android.support.v7.widget.AppCompatTextView;
import android.text.format.DateFormat;
import android.util.AttributeSet;
import java.util.Calendar;
public class DigitalClock extends AppCompatTextView {
Calendar mCalendar;
private FormatChangeObserver mFormatChangeObserver;
private Runnable mTicker;
private Handler mHandler;
private boolean mTickerStopped = false;
String mFormat;
public DigitalClock(Context context) {
super(context);
initClock();
}
public DigitalClock(Context context, AttributeSet attrs) {
super(context, attrs);
initClock();
}
private void initClock() {
if (mCalendar == null) {
mCalendar = Calendar.getInstance();
}
}
#Override
protected void onAttachedToWindow() {
mTickerStopped = false;
super.onAttachedToWindow();
mFormatChangeObserver = new FormatChangeObserver();
getContext().getContentResolver().registerContentObserver(
Settings.System.CONTENT_URI, true, mFormatChangeObserver);
setFormat();
mHandler = new Handler();
mTicker = new Runnable() {
public void run() {
if (mTickerStopped) return;
mCalendar.setTimeInMillis(System.currentTimeMillis());
setText(DateFormat.format(mFormat, mCalendar));
invalidate();
long now = SystemClock.uptimeMillis();
long next = now + (1000 - now % 1000);
mHandler.postAtTime(mTicker, next);
}
};
mTicker.run();
}
#Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
mTickerStopped = true;
getContext().getContentResolver().unregisterContentObserver(
mFormatChangeObserver);
}
private void setFormat() {
mFormat = "dd MMM yy , hh:mm ss a ";
}
private class FormatChangeObserver extends ContentObserver {
public FormatChangeObserver() {
super(new Handler());
}
#Override
public void onChange(boolean selfChange) {
setFormat();
}
}
#Override
public CharSequence getAccessibilityClassName() {
//noinspection deprecation
return DigitalClock.class.getName();
}
}
I'm first using Android Preferences and encountered unexpected problem.
I'm extend DialogPreference class and all works fine except one thing: in method onDialogClosing(boolean positiveResult) I'm receiving false no matter what button I'v pressed.
What I'm doing wrong?
Whole code of the class is listed below.
package edu.kpi.ept.labwork1;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.TypedArray;
import android.preference.DialogPreference;
import android.util.AttributeSet;
import android.view.View;
import android.widget.EditText;
public class PositivePickerPreference extends DialogPreference {
private static int DEFAULT_VALUE = 0;
private int selectedValue;
private EditText intEdit;
public PositivePickerPreference(Context context, AttributeSet attrs) {
super(context, attrs);
this.setDialogLayoutResource(R.layout.int_pick_pref_dialog);
this.setPositiveButtonText(R.string.preference_ok);
this.setNegativeButtonText(R.string.preference_cancel);
}
#Override
protected void onBindDialogView(View view) {
super.onBindDialogView(view);
intEdit = (EditText) view.findViewById(R.id.intEdit);
selectedValue = getPersistedInt(DEFAULT_VALUE);
intEdit.setText(Integer.toString(selectedValue));
}
public void onClick (DialogInterface dialog, int which) {
super.onClick();
selectedValue = Integer.parseInt(intEdit.getText().toString());
}
#Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (positiveResult) {
persistInt(selectedValue);
}
}
#Override
protected void onSetInitialValue(boolean restorePersistedValue, Object defaultValue) {
super.onSetInitialValue(restorePersistedValue, defaultValue);
if (restorePersistedValue) {
selectedValue = getPersistedInt(DEFAULT_VALUE);
} else {
selectedValue = (Integer) defaultValue;
persistInt(selectedValue);
}
}
#Override
protected Object onGetDefaultValue(TypedArray a, int index) {
return a.getInteger(index, DEFAULT_VALUE);
}
}
Just had this same issue. Its because of the onClick handler:
public void onClick (DialogInterface dialog, int which) {
super.onClick();
selectedValue = Integer.parseInt(intEdit.getText().toString());
}
Remove it, and you won't have the issue. If you need to know the button pressed, then just check the button type in that event handler block. For example
#Override
public void onClick(DialogInterface dialog, int which) {
buttonPress = which;
}
#Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (buttonPress == DialogInterface.BUTTON_NEGATIVE) {
String computerName = _etComputerName.getText().toString();
SharedPreferences computers = _context.getSharedPreferences(
"COMPUTERS", 0);
SharedPreferences.Editor editor = computers.edit();
editor.remove(computerName);
editor.commit();
this.callChangeListener(-1);
}
}
I am using kinvey as my backend where I have a collection and would like to fetch data using appData.get. I have tried using the code below but it doesnt work. Could someone please tell me whats wrong with it.
package com.example.kinvey;
import com.kinvey.android.AsyncAppData;
import com.kinvey.android.callback.KinveyListCallback;
import com.kinvey.java.core.KinveyClientCallback;
import android.app.Activity;
import android.content.Entity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
public class ActionData extends Activity{
//protected static final String TAG = "LOG:";
public static final String TAG = "ActionData";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.display);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
return super.onCreateOptionsMenu(menu);
}
public void onLoadClick(View view) {
AsyncAppData<Entity> myevents = MainActivity.mKinveyClient.appData("events",Entity.class);
myevents.get(new KinveyListCallback<Entity>() {
#Override
public void onSuccess(Entity[] result) {
Log.v(TAG, "received "+ result.length + " events");
}
#Override
public void onFailure(Throwable error) {
Log.e(TAG, "failed to fetch all", error);
}
});
}
And this is my Entity class.
package com.example.kinvey;
import com.google.api.client.json.GenericJson;
import com.google.api.client.util.Key;
import com.kinvey.java.model.KinveyMetaData;
public class Entity extends GenericJson{
#Key("_id")
private String id;
#Key("_class")
private String _class;
#Key("author")
private String author;
#Key("relatedObj")
private String relatedObj;
#Key("relatedObjName")
private String relatedObjName;
#Key("type")
private String type;
#Key("_kmd")
private KinveyMetaData meta;
#Key("_acl")
private KinveyMetaData.AccessControlList acl;
public Entity(){}
public String getActionId() {
return id;
}
public void setActionId(String id) {
this.id = id;
}
public String getclass() {
return _class;
}
public void setclass(String _class) {
this._class = _class;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getRelatedObj() {
return relatedObj;
}
public void setRelatedObj(String relatedObj) {
this.relatedObj = relatedObj;
}
public String getRelatedObjName() {
return relatedObjName;
}
public void setRelatedObjName(String relatedObjName) {
this.relatedObjName = relatedObjName;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
this here is driving me nuts...
I want to pass some Parameters with a Button Constructor
I did create myButton extending Button:
package com.canbluetoothinterface.utilities;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import android.view.View.OnClickListener;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class myActivityStartButton extends Button implements OnClickListener {
protected EditText[] Array;
private String Name;
private String BufferName;
private Activity activityinstance;
public String[] sValues;
Class<?> cls;
private Method m;
public myActivityStartButton(String Name, Class<?>clsin, Context context) {
super(context);
cls = clsin;
activityinstance = (Activity) context;
setId(mygetId());
this.Name = Name;
init();
}
private void init(){
setOnClickListener(this);
}
public myActivityStartButton(String Name, Class<?>clsin, Context context, Method min) {
super(context);
this.cls = clsin;
this.Name = Name;
this.m = min;
activityinstance = (Activity) context;
setId(mygetId());
setTag(findViewById(mygetId()));
init();
}
#Override
public void setId(int id) {
super.setId(id);
}
private int mygetId() {
int id = 0;
BufferName = Name;
id = activityinstance.getResources().getIdentifier(BufferName, "id", activityinstance.getPackageName());
return id;
}
#Override
public void onClick(View v) {
try {
m.invoke(null, (Object)null);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent intent = new Intent(activityinstance, cls );
activityinstance.startActivity(intent);
}
}
In my Activity I call:
Start = new myActivityStartButton("act_testdriveconfiguration_btn_start", DeviceListActivity.class, this, mstartbutton);
But my OnClick is never called...
What am I doing wrong?
Thank you
1.double check your init() is called.
The following code works for me.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RelativeLayout layout = (RelativeLayout) findViewById(R.id.main_container);
SomeButton btn = new SomeButton(this);
layout.addView(btn);
}
private class SomeButton extends Button implements OnClickListener {
public SomeButton(Context context) {
super(context);
init();
}
private void init() {
setOnClickListener(this);
}
#Override
public void onClick(View v) {
Log.w("log", "click");
}
}
NOTE:
if your button is created in xml, you need these constructors.
public setParams(String Name, Class<?>clsin,etc params)
{
//saving params
}
public SomeButton(Context context) {
super(context);
init();
}
public SomeButton(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public SomeButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}