I'd appreciate if you could advise on my problem.
I'm working on AR app using Vuforia SDK for Unity3D and Android plugins.
I have several ImageTargets and 3D models on my scene.
My class that works with android plugin looks like this:
public class AssetBundleAugmenter : MonoBehaviour, ITrackableEventHandler
{
void Start()
{
StartCoroutine(DownloadAndCache());
mTrackableBehaviour = GetComponent<TrackableBehaviour>();
if (mTrackableBehaviour)
{
mTrackableBehaviour.RegisterTrackableEventHandler(this);
}
init();
}
public void OnTrackableStateChanged(
TrackableBehaviour.Status previousStatus,
TrackableBehaviour.Status newStatus)
{
if (newStatus == TrackableBehaviour.Status.DETECTED ||
newStatus == TrackableBehaviour.Status.TRACKED ||
newStatus == TrackableBehaviour.Status.EXTENDED_TRACKED)
{
if (!mAttached && mBundleInstance)
{
// if bundle has been loaded, let's attach it to this trackable
//...
}
OnTrackingFound();
}
else
{
OnTrakingLost();
}
}
private void OnTrackingFound()
{
if (mTrackableBehaviour is ImageTargetAbstractBehaviour)
{
GetJavaObject().Call("OnMarkerFound");
}
}
void onButtonClicked(int index)
{
//Changing current 3D model material
}
#if UNITY_ANDROID
private AndroidJavaObject javaObj = null;
//LISTENING TO BUTTON CLICK EVENTS FROM ANDROID
private sealed class EventListner : AndroidJavaProxy
{
private AssetBundleAugmenter mReceiver;
public EventListner(AssetBundleAugmenter receiver)
: base("com.mypackage.myapp.ImageTargetTracker$Listner")
{
mReceiver = receiver;
}
public void onButtonClicked(int index) //change color of model
{
mReceiver.onButtonClicked(index);
}
}
private AndroidJavaObject GetJavaObject()
{
if (javaObj == null)
{
javaObj = new AndroidJavaObject("com.mypackage.myapp.ImageTargetTracker");
}
return javaObj;
}
AndroidJavaObject activity;
private void init()
{
// Retrieve current Android Activity from the Unity Player
AndroidJavaClass jclass = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
activity = jclass.GetStatic<AndroidJavaObject>("currentActivity");
// Pass reference to the current Activity into the native plugin,
GetJavaObject().Call("setActivity", activity, new EventListner(this));
}
#else
void init() {}
#endif
}
So I attached this script to all of my ImageTargets on the scene, which I know must be wrong, because UnityPlayer gets initialized several times in my init() function.
I tried to attach the script to ARCamera on my scene, and write initialization only there, but I'm not sure how to access currentActivity in scripts that work with ImageTargets. Also, I use listener - the interface in my plugin that listens to button clicks to fire some functionality in unity.
My plugin code:
public class ImageTargetTracker {
public static interface Listner {
public void onButtonClicked(int index);
}
private Listner mListner;
protected Activity mCurrentActivity;
public void setActivity(Activity activity, Listner listner)
{
mCurrentActivity = activity;
mListner = listner;
mCurrentActivity.runOnUiThread(new Runnable() {
public void run() {
LayoutInflater inflater = mCurrentActivity.getLayoutInflater();
Resources resources = mCurrentActivity.getResources();
String pkgName = mCurrentActivity.getPackageName();
int id = resources.getIdentifier("camera_layout", "layout", pkgName);
View view = inflater.inflate(id, null);
mCurrentActivity.addContentView(view, param);
//INITIALIZING UI ELEMENTS HERE (DISPLAYED ON TOP OF CAMERA)
}
public void OnMarkerFound(){
mCurrentActivity.runOnUiThread(new Runnable() {
public void run() {
//Showing some UI elements
}
});
}
}
So, how can I globally initialize the Activity and my plugin class in Unity one time, and use them in all of my scripts?
As discussed in the comments, I recommend using the singleton pattern.
Related
I have this code separate class which makes a Snackbar to be displayed within my application, But with my current implementation I am getting a 'java.lang.NullPointerException'. How do I implement it in my main class properly?
here is my snack bar class:
public class SnackBarUtils
{
private static SnackBarUtils mInstance = null;
private Snackbar mSnackBar;
private SnackBarUtils()
{
}
public static SnackBarUtils getInstance()
{
if (mInstance == null)
{
mInstance = new SnackBarUtils();
}
return mInstance;
}
public void hideSnackBar()
{
if (mSnackBar != null)
{
mSnackBar.dismiss();
}
}
public void showProblemSnackBar(final Activity activity, final String message)
{
mSnackBar = Snackbar.make(activity.findViewById(android.R.id.content), message,
Snackbar.LENGTH_INDEFINITE);
// Changing action button text color
View sbView = mSnackBar.getView();
TextView textView = sbView.findViewById(com.google.android.material.R.id.snackbar_text);
mSnackBar.setAction("x", new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//Call your action method here
mSnackBar.dismiss();
}
});
textView.setTextColor(Color.WHITE);
sbView.setBackgroundColor(Color.RED);
textView.setMaxLines(3);
mSnackBar.show();
}
}
This is my current implementation within main activity, I have already Initialized the snackbar class like this:
SnackBarUtils snackBarUtils;
and then called it like this:
snackBarUtils.showProblemSnackBar(MainActivity.this, mPlainTextResponse);
what am I doing wrong? Or what is the correct way to do this?
First of all, you would share the stacktrace of the NPE for more context.
For the snackbar utility:
If you are using callbacks, then you can use the utility for displaying a snackbar with that callback as parameter:
interface onProblemSnackbarClickedListener {
void onActionClicked(View view);
}
...
/* inside SnackBarUtils.java */
...
public static void showProblemSnackbar(View view, #StringRes int message, onProblemSnackbarClickedListener listener){
Snackbar mSnackBar = Snackbar.make(view,message,Snackbar.LENGTH_INDEFINITE)
.setAction("x", new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onActionClicked(v);
mSnackBar.dismiss();
}
})
mSnackbar.show();
}
The callback could work for the need to listen to it in the activity/fragment.
For the styling of the Snackbar, you can see this related question:
Style SnackBar in theme app.
Keep in mind the migration from "Support design" to MDC (Material design components), that facilitates the global styling of the snackbar with theme attributes.
I followed this article and pieced together information with other articles to create a splash screen:
https://learn.microsoft.com/en-us/xamarin/android/user-interface/splash-screen
The splash screen works well when I start the app up by tapping on the app's icon. However, if the app is already running and I switch to it, the screen goes white for a few seconds while the app resumes. Why?
Here is my code:
[Activity(Label = "Hardfolio", Icon = "#drawable/icon", Theme = "#style/MyTheme.Splash", MainLauncher = true, NoHistory = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class SplashActivity : FormsAppCompatActivity
{
static readonly string TAG = "Hardfolio: " + typeof(SplashActivity).Name;
public override void OnCreate(Bundle savedInstanceState, PersistableBundle persistentState)
{
base.OnCreate(savedInstanceState, persistentState);
}
// Launches the startup task
protected override void OnResume()
{
base.OnResume();
var startupWork = new Task(AppStartup);
startupWork.Start();
}
// Simulates background work that happens behind the splash screen
async void AppStartup()
{
StartActivity(new Intent(Application.Context, typeof(MainActivity)));
}
}
[Activity(Label = "Hardfolio", Icon = "#drawable/icon", Theme = "#style/MainTheme", MainLauncher = false, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
[IntentFilter(new[] { UsbManager.ActionUsbDeviceAttached })]
[MetaData(UsbManager.ActionUsbDeviceAttached, Resource = "#xml/device_filter")]
public class MainActivity : Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
#region Fields
private AndroidHidDevice _TrezorHidDevice;
private UsbDeviceAttachedReceiver _UsbDeviceAttachedReceiver;
private UsbDeviceDetachedReceiver _UsbDeviceDetachedReceiver;
private object _ReceiverLock = new object();
#endregion
#region Overrides
protected override void OnCreate(Bundle bundle)
{
try
{
_TrezorHidDevice = new AndroidHidDevice(GetSystemService(UsbService) as UsbManager, ApplicationContext, 3000, 64, TrezorManager.TrezorVendorId, TrezorManager.TrezorProductId);
ServicePointManager.ServerCertificateValidationCallback += (o, certificate, chain, errors) => true;
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(bundle);
Xamarin.Forms.Forms.Init(this, bundle);
RegisterReceiver();
var application = new App(new CrossPlatformUtilities(new IsolatedStoragePersister(), new AndroidRESTClientFactory()), _TrezorHidDevice, GetPin);
LoadApplication(application);
}
catch (Exception ex)
{
Logger.Log("Android crash", ex, nameof(Wallet.Droid));
Toast.MakeText(ApplicationContext, ex.ToString(), ToastLength.Long).Show();
}
}
private async Task<string> GetPin()
{
var taskCompletionSource = new TaskCompletionSource<string>();
RunOnUiThread(async () =>
{
var pin = await TrezorPinPad.GetPin();
taskCompletionSource.SetResult(pin);
});
return await taskCompletionSource.Task;
}
protected override void OnResume()
{
base.OnResume();
Logger.Log($"Resuming... Setting up Trezor listeners. _TrezorHidDevice is {(_TrezorHidDevice == null ? "null" : "not null")}", null, nameof(Wallet.Droid));
RegisterReceiver();
}
private void RegisterReceiver()
{
try
{
lock (_ReceiverLock)
{
if (_UsbDeviceAttachedReceiver != null)
{
UnregisterReceiver(_UsbDeviceAttachedReceiver);
_UsbDeviceAttachedReceiver.Dispose();
}
_UsbDeviceAttachedReceiver = new UsbDeviceAttachedReceiver(_TrezorHidDevice);
RegisterReceiver(_UsbDeviceAttachedReceiver, new IntentFilter(UsbManager.ActionUsbDeviceAttached));
if (_UsbDeviceDetachedReceiver != null)
{
UnregisterReceiver(_UsbDeviceDetachedReceiver);
_UsbDeviceDetachedReceiver.Dispose();
}
_UsbDeviceDetachedReceiver = new UsbDeviceDetachedReceiver(_TrezorHidDevice);
RegisterReceiver(_UsbDeviceDetachedReceiver, new IntentFilter(UsbManager.ActionUsbDeviceDetached));
}
}
catch (Exception ex)
{
Logger.Log($"Error registering Hid receivers", ex, nameof(Wallet.Droid));
}
}
#endregion
}
If you start your application, from within another application/or using the ClearTask flag/or if your app is performing a cold start (has been closed in the background), and perhaps i other ways as well, you will see a "Preview" screen, which is the background of your current theme (kind of what you are already doing for your SplashScreen, which shows the theme background)...
But if your "#style/MainTheme" has a simple white background, this will be what you might see when reentering your app.
Therefore you can consider using the "SetTheme" method in OnCreate. There is more about this in this link:
https://developer.android.com/topic/performance/vitals/launch-time
Hope it helps.
I decide to learn about MVP pattern and after look through some articles i want to try it with my current project.
I have choosen one activity and begin to think how i can decouple it according MVP rules. And eventually I don't know how to do it. It seems like a not complicated activity but I don't know
Could please someone adviced me with what I have to start?
Which methods have to be in presenter, witch view have to be left in this current activity and whitch methods have to be in interface?
Just advised me who i supposed to begin.
This is my class
public final class ActivityUserDataScreen extends AppCompatActivity implements InterfaceActivityUserDataScreen{
private static String gender;
private static int inputHeight;
private static int inputWeight;
private TextInputLayout tilUserName;
private int backPressedQ = 0;
private String avatarName;
private static final String MEN = "men";
private static final String WOMEN = "men";
private Context context;
private PresenterActivityUserDataScreen presenter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fabric.with(this, new Crashlytics());
setContentView(R.layout.activity_user_data_screen);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setSupportActionBar((Toolbar) findViewById(R.id.tool_bar));
context = getApplicationContext();
initNumberPicker();
initVar();
presenter = new PresenterActivityUserDataScreen(this);
}
private void initNumberPicker() {
NumberPicker pickerHeight = (NumberPicker) findViewById(R.id.pickerHeight);
UtilClass.setDividerColor(pickerHeight, UtilClass.getMyColor(context, R.color.ntz_color_yellow));
pickerHeight.setOnValueChangedListener(changeListener);
pickerHeight.setMaxValue(220);
pickerHeight.setMinValue(130);
pickerHeight.setValue(States.HEIGHT_DEFAULT);
NumberPicker pickerWeight = (NumberPicker) findViewById(R.id.pickerWeight);
UtilClass.setDividerColor(pickerWeight, UtilClass.getMyColor(context, R.color.ntz_color_yellow));
pickerWeight.setOnValueChangedListener(changeListener);
pickerWeight.setMaxValue(120);
pickerWeight.setMinValue(35);
pickerWeight.setValue(States.WEIGHT_DEFAULT);
}
private void initVar() {
tilUserName = (TextInputLayout) findViewById(R.id.tilUserName);
SwitchButton switchButton = (SwitchButton) findViewById(R.id.sb_custom);
switchButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
gender = WOMEN;
}else {
gender = MEN;
}
}
});
EditText etAvatarName = (EditText) findViewById(R.id.etAvatarName);
etAvatarName.setText(getResources().getString(R.string.avatar));
}
private NumberPicker.OnValueChangeListener changeListener = new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
switch (picker.getId()) {
case R.id.pickerHeight:
inputHeight = newVal;
break;
case R.id.pickerWeight:
inputWeight = newVal;
break;
}
}
};
#Override
public final void onBackPressed() {
UtilClass.processClick(context);
if (backPressedQ == 1) {
backPressedQ = 0;
super.onBackPressed();
overridePendingTransition(R.anim.open_main, R.anim.close_next);
} else {
backPressedQ++;
Toast.makeText(this, "Press again to exit", Toast.LENGTH_SHORT).show();
}
//Обнуление счётчика через 5 секунд
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
backPressedQ = 0;
}
}, 5000);
}
public final void goNext(View view) {
UtilClass.processClick(context);
EditText editText = tilUserName.getEditText();
Editable editable = null;
if (editText != null) {
editable = editText.getText();
}
if (editable != null) {
avatarName = editable.toString();
}
if (!isValidAvatarName()) return;
saveUserData();
MetadataSaver saver = new MetadataSaver(context);
saver.saveFirstUserInfo();
saver.saveDeviceInfo();
PreferencesHelper.savePref(context, States.STILL_NOT_FINISH, true);
UtilClass.goToNextActivity(ActivityUserDataScreen.this, ActivityVideo.class);
}
private void saveUserData(){
saveAvatarGender();
saveAvatarHeight();
saveAvatarWeight();
saveAvatarName();
}
private void saveAvatarGender(){
if (gender == null){
gender = MEN;
}
PreferencesHelper.savePref(context, States.AVATAR_GENDER, gender);
}
private boolean isValidAvatarName() {
if (UtilClass.isTextEmpty(avatarName)) {
tilUserName.setErrorEnabled(true);
tilUserName.setError(getResources().getString(R.string.fill_your_avatar_name));
return false;
}
if (avatarName.contains(" ")) {
avatarName = avatarName.replace(" ", "");
}
if (!UtilClass.isLatinAlphabet(avatarName)) {
tilUserName.setErrorEnabled(true);
tilUserName.setError(getResources().getString(R.string.avatar_name_in_english));
return false;
}
if (!UtilClass.isNameFree(context, avatarName)) {
tilUserName.setErrorEnabled(true);
tilUserName.setError(getResources().getString(R.string.avatar_name_already_in_use));
return false;
}
return true;
}
private void saveAvatarHeight() {
int result;
if (inputHeight == 0) {
result = States.HEIGHT_DEFAULT;
} else {
result = inputHeight;
}
PreferencesHelper.savePref(context, States.AVATAR_HEIGHT, result);
}
private void saveAvatarWeight() {
int result;
if (inputWeight == 0) {
result = States.WEIGHT_DEFAULT;
} else {
result = inputWeight;
}
PreferencesHelper.savePref(context, States.AVATAR_WEIGHT, result);
}
private void saveAvatarName() {
PreferencesHelper.savePref(context, States.AVATAR_NAME, avatarName);
}
public final void switchManWoman(View view) {
UtilClass.processClick(context);
}
}
Thanks in advance!
The things to take into account are:
The view needs to be as dumb as possible. Think of it as an executor of the commands given by the presenter, and reporter to the presenter of all the stuff that happened on the UI. The interface should provide methods like "display this text", and / or calling presenter's methods like "the button was clicked".
the presenter is the one in command. It drives your view behaviour and reacts to the inputs coming from the view itself. Ideally, it should abstract from anything Android related, in this way you can test the behaviour inside vanilla tests.
Google has published a collection of samples to discuss and showcase different architectural tools and patterns for Android apps.
To begin, very usefull to you to understand how this one works. And adapt to your sample.
[...] This sample is the base for many of the variants. It showcases a simple implementation of the Model-View-Presenter pattern with no architectural frameworks. It uses manual dependency injection to provide a repository with local and remote data sources. Asynchronous tasks are handled with callbacks [...]
I highly recommend reading this article on medium: https://medium.com/#tinmegali/model-view-presenter-mvp-in-android-part-1-441bfd7998fe#.f4yiylrwa .
In essence, all things related to the android SDK should be put in your "view" (and occasionally your model), which will usually be a fragment or activity. Figuring out the difference between your model and presenter will be more up to you, however, you can think about your presenter as the thing that makes program logic decisions based on inputs to your application. Often, the mvp pattern is used in Android development to try to get around rotation and activity recreation issues so you may have luck using a static presenter for a small sample application.
Best of luck!
Hi there StackOverflow!
I had been loocking on a way to Use the native Android Dialogs and Confimation Boxes in Libgdx...
All that i did by now was a Title and an Image under it:
Dialog yourmsgbox = new Dialog("Title", jsons);
yourmsgbox.setBounds(0f,0f,100f,200f);
yourmsgbox.add(choiceImg);
mainClass.addActor(yourmsgbox);
I suck a little at this but all the codes that i find in Google to do that are Or for Desktop or very especific for that Type of game + Even after some tries to copy the code and adapt it to my .java Files im still getting errors....
So if you guys could guide through a step by step ((Or a list Number of online items that i could follow to get this done I WOULD BE VERYY GRATEFULL !!!))
[[My Json file is EXTREMELY BUGGY, so if I could not have to mess with that Stubborn uiskin.json, I would Thank you :]]
Sorry my bad english
Please i'd apreciate a little help!?
UPDATE:: Sorry i have
two MainClasses for this project and i pick the wrong Logcat :)
I just use showMessage(); in the beggining of the create(), it
crashes when i get into the app. Here is what i did:
I Created an Inferface in core Project:
public interface NativeDialogInterface {
void showMessage(final String title, final String message, final String okButtonText);
}
Created AndroidNativeDialog in -android Project folder:
public class AndroidNativeDialog implements NativeDialogInterface {
private Activity activity;
public void initialize(Activity activity) {
this.activity = activity;
}
#Override
public void showMessage(final String title, final String message, final String okButtonText) {
this.activity.runOnUiThread(new Runnable() {
#Override
public void run() {
final AlertDialog alertDialog = new AlertDialog.Builder(activity).create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setButton(okButtonText, new DialogInterface.OnClickListener() {
#Override
public void onClick(final DialogInterface arg0, final int arg1) {
alertDialog.cancel();
}
});
alertDialog.show();
}
});
}
}
*Strange that it says as warning "Method setButton(...) is deprecated"
Then i added new (dialogInterface) in the AndroidLaucher.java:
public class AndroidLauncher extends AndroidApplication {
private AndroidNativeDialog dialogInteface;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
dialogInterface = new AndroidNativeDialog();
initialize(new IndexMain(dialogInteface), config);
}
}
Then in the MainClass what i did was:
btnWindow.addListener(new ClickListener(){
#Override
public void clicked(InputEvent event, float x, float y) {
mainScreen.addActor(andWindow);
dialogInteface.showMessage("TITLE", "ThE MeSsaGe", "Okayy");
Timer.schedule(new Timer.Task() {
#Override
public void run() {
andWindow.setBounds(Gdx.graphics.getWidth(), 0f, 1f, 1f);
}
}, 17);
}
});
I head to that link that "Fuat Coçkun" provided and i learn a lot about these type of structures but it seems i still have something wrongg
Its WORKS perfectly until i click that /\ Button, the button is ok if i delete the showMessage(...);
new LogCat: http://pastebin.com/NbgnyrAJ
Sorry for my bad english.
I can give you example usage of native android AlertDialog with libgdx. Firstly you need an interface in your core Project as follows :
public interface NativeDialogInterface {
void showMessage(final String title, final String message, final String okButtonText);
}
You need different implementations for each of platform you support in your project. Android project implementation will use Dialog, AlertDialog or whatever you want to use as native android component. This example shows AlertDialog implementation:
public class AndroidNativeDialog implements NativeDialogInterface {
private Activity activity;
public void initialize(Activity activity) {
this.activity = activity;
}
#Override
public void showMessage(final String title, final String message, final String okButtonText) {
this.activity.runOnUiThread(new Runnable() {
#Override
public void run() {
final AlertDialog alertDialog = new AlertDialog.Builder(activity).create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setButton(okButtonText, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
alertDialog.cancel();
}
});
alertDialog.show();
}
});
}
}
You need to call "initialize" method of your instance in your activity(onCreate is proper.) for setting activity field.
You can use any dummy implementation for the Desktop module of your libgdx project. Following implementation only logs the data you passed.
public class DesktopNativeDialog implements NativeDialogInterface {
#Override
public void showMessage(final String title, final String message, final String okButtonText) {
System.out.println("Title : " + title);
System.out.println("Message : " + message);
System.out.println("OkButtonText : " + okButtonText);
}
}
That's all. You should have a field typed NativeDialogInterface in your Core module and call "showMessage" method with your parameter. You will see a console log if you run your application on desktop. You will see native Android alert dialog on your glSurfaceView when you run your application on device/emulator.
I did this and created an expansion for libGDX. You can use it or check the source: https://github.com/TomGrill/gdx-dialogs
I'm writing an app for the Sony Smartwatch, using their SDK. Here's part of the main activity:
class SmartTickerActivity extends ControlExtension {
private Handler mHandler;
SmartTickerActivity(final String hostAppPackageName, final Context context, Handler handler) {
super(context, hostAppPackageName);
if (handler == null) {
throw new IllegalArgumentException("handler == null");
}
}
#Override
public void onStart() {
//do some stuff
PreferenceManager.setDefaultValues(mContext, R.xml.preference, false);
}
The problem is that the saved preferences aren't being applied on the Smartwatch when the application launches. Nor are the default preference values from XML. However, if I click on any of the app's preferences on the phone, the saved preference values are immediately applied to the Smartwatch.
Note that the main class has no onCreate() method, and that's throwing me for a loop.
Here's part of the Preference activity:
public class MyPreferenceActivity extends PreferenceActivity {
private OnSharedPreferenceChangeListener mListener = new OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Preference pref = findPreference(key);
if (pref instanceof ListPreference) {
ListPreference listPref = (ListPreference) pref;
pref.setSummary(listPref.getEntry().toString());
}
if (pref instanceof EditTextPreference) {
EditTextPreference editTextPref = (EditTextPreference) pref;
pref.setSummary(editTextPref.getText().toString());
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preference);
setSummaries();
setTypeface(SmartTickerActivity.mainLayout);
if (previewLayout != null) setTypeface(previewLayout);
// Handle read me
Preference readMe = findPreference(getText(R.string.preference_key_read_me));
readMe.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference readMe) {
showDialog(DIALOG_READ_ME);
return true;
}
});
// Handle about
Preference about = findPreference(getText(R.string.preference_key_about));
about.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference about) {
showDialog(DIALOG_ABOUT);
return true;
}
});
// Handle preview
Preference preview = findPreference(getText(R.string.preference_key_preview_dialog));
preview.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preview) {
showDialog(DIALOG_PREVIEW);
return true;
}
});
}
I'm rather inexperienced at Android development, so the problem might very well have nothing to do whatsoever with the Sony SDK. Can anyone help?
You are correct, the preferences of the official sample extensions are not loaded until the PreferenceActivity is shown for the first time. If you use correct default values when accessing the preferences, this should not be a problem.
If you would like for the preferences to be loaded when the extension is initiated the first time, you could extend the android.app.Application class, and the onCreate method.
For example:
public class MySmartWatchApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
PreferenceManager.setDefaultValues(this, R.xml.app_preferences, false);
}
}