How to make checkboxes work in a live wallpaper Android app? - android

I have three check boxes in my live wallpaper's settings that I need to figure out how to make them work, I want for example checkbox1 to execute code1, checkbox2 to execute code 2 and the last checkbox to execute code3:
code1:
private void incrementCounter() {
if (mImagesArrayIndex >= mImagesArray.length-10) {
mImagesArrayIndex = mImagesArray.length-10;}
if (mImagesArrayIndex <10) {
mImagesArrayIndex = 10;
code2:
private void incrementCounter() {
if (mImagesArrayIndex >= mImagesArray.length-20) {
mImagesArrayIndex = 0;}
if (mImagesArrayIndex <0) {
mImagesArrayIndex = mImagesArray.length-20;
}
}
code3:
mImagesArrayIndex++;
code3 (goes into code1 and code2), codes1,2,3 are all in CustomWallpaper.java That's all, I have already set my settings layout and it looks like this:

solution:
public void run() {
SharedPreferences myPref = PreferenceManager.getDefaultSharedPreferences( CustomWallpaper.this);
try {
while (true) {
drawFrame();
if (myPref.getBoolean("lwp_o_scroll_lock_key",true))
incrementCounter1();
else
incrementCounter2();
if (myPref.getBoolean("lwp_auto_animation_key",true))
mImagesArrayIndex++;
else
//
// if (myPref.getBoolean("lwp_auto_animation_key",true))
//incrementCounter2();
Thread.sleep(SeekBarPreference.mCurrentValue);
}
} catch (Exception e) {
//
}
}

Related

Android Studio and JavaFx

Hi im Java\JavaFx\Android-Studio beginner
i wrote a little app in JavaFx, it works fine, now i try to run it on a Smartphone with Android Studio.
Most of this code Works, but i have a problem with my for Loop, it doesnt work, and i dont know why :(
The foundWords List remains empty...
But on my Source Projekt in JavaFx it still works.
public class MainActivity extends AppCompatActivity {
String word;
String list;
char[] wordChars;
List<String> wordList = new ArrayList<String>();
EditText input;
TextView output;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
input = (EditText) findViewById(R.id.input);
output = (TextView) findViewById(R.id.output);
}
/*
Read Textfile
*/
public void readTextfile() {
BufferedReader read = null;
try {
read = new BufferedReader(
new InputStreamReader(getAssets().open("test.txt")));
Arrays.asList(wordList);
while ((list = read.readLine()) != null) {
wordList.add(list);
}
read.close();
} catch (Exception e) {
e.getMessage();
}
Log.i("ListRead", "Done"); }
public static int getNumValue(char[] string, char val) {
int count = 0;
for (char c : string) {
if (c == val) {
count++;
}
}
return count;
}
public static boolean notTooManyLetters(char[] word, char[] wordChars) {
for (char letter : wordChars) {
if (getNumValue(word, letter) > getNumValue(wordChars, letter)) {
return false;
}
}
return true;
}
public static boolean sameLetters(char[] w, char[] wordChars) {
for (char letter : w) {
if (new String(wordChars).indexOf(letter) < 0) {
return false;
}
}
return true;
}
// Create Result
public void compare() {
List<String> foundWords = new ArrayList<String>();
word = input.getText().toString().toUpperCase();
wordChars = word.toCharArray();
for (String w : wordList) {
for (char letter : wordChars) {
if (word.indexOf(letter) > 0 && foundWords.indexOf(w) < 0 && w.length() <= wordChars.length
&& notTooManyLetters(w.toCharArray(), wordChars) && sameLetters(w.toCharArray(), wordChars)) {
foundWords.add(w);
} else {
if (foundWords.size() <= 0) {
Log.i("CheckList", "Empty List!");
}
}
}
}
output.setText(foundWords.toString());
}
public void onKlickAbc(View view) {
readTextfile();
compare();
}}
It seems like your code simply never executes.
Your activity overrides lifecycle methods and those are the only methods the OS is going to call. Any other methods are useless if not linked or triggered from these lifecycle methods.
Indeed, in Android you don't have access to a "main loop" like in other UI frameworks. Please refer to https://developer.android.com/guide/components/activities/intro-activities#mtal
PS: welcome to SO :)

ZXing-embedded library scans irrelevant/wrong bar-code values in some cases

I've implemented native ZXing-embedded library in my Xamarin.Android project and everything's working fine except one issue that when I try to scan the QR or Barcodes from some distance, then it returns some random irrelevant values which are totally different from the original ones. After checking this post I've tried restricting the scan modes but it made no difference and it is still returning wrong values. Any help would be really appreciable.
Thanks in advance!
Update 2:
Here's is my code, you can check and let me know if there's something that needs to be corrected in it:
public class CustomScannerActivity : Activity, DecoratedBarcodeView.ITorchListener
{
public const int CUSTOMIZED_REQUEST_CODE = 1;
private CaptureManager capture;
private DecoratedBarcodeView barcodeScannerView;
private ImageButton switchFlashlightButton;
private ImageButton cameraButton;
private ViewfinderView viewfinderView;
TextView txtViewBottomText;
private bool torchOn;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
this.ActionBar.Hide();
SetContentView(Resource.Layout.activity_custom_scannerview);
barcodeScannerView = (DecoratedBarcodeView)FindViewById(Resource.Id.zxing_barcode_scanner);
barcodeScannerView.SetTorchListener(this);
var greenOverlay = (View)FindViewById(Resource.Id.view1);
Android.Util.DisplayMetrics displayMetrics = Resources.DisplayMetrics;
var scanWidth = (int)(displayMetrics.WidthPixels * 0.65);
barcodeScannerView.BarcodeView.FramingRectSize = new Size(scanWidth, 100);
greenOverlay.LayoutParameters.Width = scanWidth;
greenOverlay.LayoutParameters.Height = scanWidth;
CameraSettings settings = barcodeScannerView.BarcodeView.CameraSettings;
switchFlashlightButton = (ImageButton)FindViewById(Resource.Id.switch_flashlight);
cameraButton = (ImageButton)FindViewById(Resource.Id.camera);
viewfinderView = (ViewfinderView)FindViewById(Resource.Id.zxing_viewfinder_view);
txtViewBottomText = (TextView)FindViewById(Resource.Id.zxing_status_view);
txtViewBottomText.Text = AppResources.ScanAutomatically;
if (MainActivity.camPosition)
{
settings.RequestedCameraId = Convert.ToInt32(Android.Hardware.CameraFacing.Front);
switchFlashlightButton.Visibility = ViewStates.Gone;
barcodeScannerView.BarcodeView.CameraSettings = settings;
barcodeScannerView.Resume();
}
else
{
settings.RequestedCameraId = Convert.ToInt32(Android.Hardware.CameraFacing.Back);
switchFlashlightButton.Visibility = ViewStates.Visible;
barcodeScannerView.BarcodeView.CameraSettings = settings;
barcodeScannerView.Resume();
}
switchFlashlightButton.Click += (s, e) =>
{
if (!torchOn && !MainActivity.camPosition)
{
barcodeScannerView.SetTorchOn();
}
else
{
barcodeScannerView.SetTorchOff();
}
torchOn = !torchOn;
};
cameraButton.Click += (s, e) =>
{
//CameraSettings settings = barcodeScannerView.BarcodeView.CameraSettings;
if (barcodeScannerView.BarcodeView.IsPreviewActive)
{
barcodeScannerView.Pause();
}
//swap the id of the camera to be used
if (settings.RequestedCameraId == Convert.ToInt32(Android.Hardware.CameraFacing.Front))
{
settings.RequestedCameraId = Convert.ToInt32(Android.Hardware.CameraFacing.Back);
switchFlashlightButton.Visibility = ViewStates.Visible;
barcodeScannerView.SetTorchOff();
MainActivity.camPosition = false;
barcodeScannerView.BarcodeView.CameraSettings = settings;
barcodeScannerView.Resume();
}
else
{
settings.RequestedCameraId = Convert.ToInt32(Android.Hardware.CameraFacing.Front);
switchFlashlightButton.Visibility = ViewStates.Gone;
barcodeScannerView.SetTorchOff();
MainActivity.camPosition = true;
barcodeScannerView.BarcodeView.CameraSettings = settings;
barcodeScannerView.Resume();
}
};
// if the device does not have flashlight in its camera,
// then remove the switch flashlight button...
if (!hasFlash())
{
switchFlashlightButton.Visibility = ViewStates.Gone;
}
capture = new CaptureManager(this, barcodeScannerView);
capture.InitializeFromIntent(Intent, savedInstanceState);
capture.Decode();
}
protected override void OnResume()
{
base.OnResume();
if (capture != null)
{
capture.OnResume();
}
}
protected override void OnPause()
{
base.OnPause();
if (capture != null)
{
capture.OnPause();
}
}
protected override void OnDestroy()
{
base.OnDestroy();
if (capture != null)
{
capture.OnDestroy();
}
}
protected override void OnSaveInstanceState(Bundle outState)
{
base.OnSaveInstanceState(outState);
if (capture != null)
{
capture.OnSaveInstanceState(outState);
}
}
//public override bool OnKeyDown([GeneratedEnum] Keycode keyCode, KeyEvent e)
//{
// return barcodeScannerView.OnKeyDown(keyCode, e) || base.OnKeyDown(keyCode, e);
//}
private bool hasFlash()
{
return this.ApplicationContext.PackageManager.HasSystemFeature(Android.Content.PM.PackageManager.FeatureCameraFlash);//"android.hardware.camera.flash"
}
public void OnTorchOff()
{
}
public void OnTorchOn()
{
}
}

Custom renderer for Tabbed page in Android: Xamarin Forms

I am working on a Xamarin.Forms application. I have this tabbed page renderer in iOS:
public class TabbedPageRenderer : TabbedRenderer
{
private MainPage _page;
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
_page = (MainPage)e.NewElement;
}
else
{
_page = (MainPage)e.OldElement;
}
try
{
var tabbarController = (UITabBarController)this.ViewController;
if (null != tabbarController)
{
tabbarController.ViewControllerSelected += OnTabBarReselected;
}
}
catch (Exception exception)
{
Console.WriteLine(exception);
}
}
private void OnTabBarReselected(object sender, UITabBarSelectionEventArgs e)
{
var tabs = Element as TabbedPage;
var playTab = tabs.Children[4];
if (TabBar.SelectedItem.Title == "Play")
{
if (tabs != null)
{
playTab.Title = "Pause";
playTab.Icon = "pause.png";
}
App.pauseCard = false;
}
else
{
if (tabs != null)
{
playTab.Title = "Play";
playTab.Icon = "play.png";
}
App.pauseCard = true;
}
}
}
This basically changes the icon on my Play tab to pause and play. This is working good in iOS. But I am struggling on how to have the same function (basically convert this to Android) in Android side.
Can any point me to the right direction? Basically help me? :-)
Note: I am pretty new with Android development.
EDIT: This is what it would look like in iOS.
Pause Mode:
Play Mode:
There is a blog post by Xamarin's James Montemagno which explains how to achieve this requirement.
Basically, it uses Custom Tab which inherits from TabbedPage which initialize an event UpdateIcons to be fired on Tab Current Page Changed event CurrentPageChanged
public class MyTabs : TabbedPage
{
//always save a reference to the current page
Page currentPage;
public MyTabs()
{
//create the pages and set the view models
//you could also do this in the page code behind
Children.Add(new TabIconsPage
{
BindingContext = new Tab1ViewModel
{
IsSelected = true
}
});
Children.Add(new TabIconsPage2
{
BindingContext = new Tab2ViewModel()
});
currentPage = Children[0];
//Register for page changes
this.CurrentPageChanged += Handle_CurrentPageChanged;
}
//Update the IsSelected state and trigger an Event that anyone can loop into.
public event EventHandler UpdateIcons;
void Handle_CurrentPageChanged(object sender, EventArgs e)
{
var currentBinding = currentPage.BindingContext as IIconChange;
if (currentBinding != null)
currentBinding.IsSelected = false;
currentPage = CurrentPage;
currentBinding = currentPage.BindingContext as IIconChange;
if (currentBinding != null)
currentBinding.IsSelected = true;
UpdateIcons?.Invoke(this, EventArgs.Empty);
}
}
Now Android needs a custom renderer to subscribe to the UpdateIcons event and perform icon changes
public class MyTabs : TabbedPage
{
//always save a reference to the current page
Page currentPage;
public MyTabs()
{
//create the pages and set the view models
//you could also do this in the page code behind
Children.Add(new TabIconsPage
{
BindingContext = new Tab1ViewModel
{
IsSelected = true
}
});
Children.Add(new TabIconsPage2
{
BindingContext = new Tab2ViewModel()
});
currentPage = Children[0];
//Register for page changes
this.CurrentPageChanged += Handle_CurrentPageChanged;
}
//Update the IsSelected state and trigger an Event that anyone can loop into.
public event EventHandler UpdateIcons;
void Handle_CurrentPageChanged(object sender, EventArgs e)
{
var currentBinding = currentPage.BindingContext as IIconChange;
if (currentBinding != null)
currentBinding.IsSelected = false;
currentPage = CurrentPage;
currentBinding = currentPage.BindingContext as IIconChange;
if (currentBinding != null)
currentBinding.IsSelected = true;
UpdateIcons?.Invoke(this, EventArgs.Empty);
}
}

Show 3dmodel after tracking lost metaio sdk

I am using metaio sdk 6.0.2. i am working on metaio INSTANT_2D_GRAVITY tracking and was able to display 3d model. I want to display same 3d model when tracking is lost.but I am failing to do so. I tried by adding trackingValuesVector in onTrackingEvent of MetaioSDKCallbackHandler with no success. can anyone tell me where am I going wrong?
private TrackingValues mTrackingValues;// declared globally
private IGeometry mModel; // declared globally
private boolean mPreview=true;// declared globally
// start INSTANT_2D_GRAVITY tracking
public void onTakePicture(View v)
{
captureTrackingValues = true;
metaioSDK.startInstantTracking("INSTANT_2D_GRAVITY", new File(""), mPreview);
mPreview = !mPreview;
}
final class MetaioSDKCallbackHandler extends IMetaioSDKCallback
{
#Override
public void onInstantTrackingEvent(final boolean success,final File filePath) {
super.onInstantTrackingEvent(success, filePath);
if(mSurfaceView != null)
{
mSurfaceView.queueEvent(new Runnable() {
#Override
public void run() {
if(success)
{
if(captureTrackingValues == true)
{
metaioSDK.setTrackingConfiguration(filePath);
Log.i("Tracking value success","good");
}
}
else
{
Log.i("Tracking value failure","bad");
}
}
});
}
}
#Override
public void onTrackingEvent(TrackingValuesVector trackingValuesVector) {
super.onTrackingEvent(trackingValuesVector);
if (!trackingValuesVector.isEmpty())
{
for(int i =0;i< trackingValuesVector.size();i++)
{
if(trackingValuesVector.get(i).isTrackingState() && mModel!=null)
{
mTrackingValues = metaioSDK.getTrackingValues(i);
mModel.setCoordinateSystemID(trackingValuesVector.get(i).getCoordinateSystemID());
}
else {
if(mModel!= null && mTrackingValues != null) {
metaioSDK.setCosOffset(1, mTrackingValues);
//mChairModel.setCoordinateSystemID(0);
Log.e("TestAR","isTrackingState is null");
}
}
}
}
else{
if(mModel!= null && mTrackingValues != null) {
metaioSDK.setCosOffset(1, mTrackingValues);
//mModel.setCoordinateSystemID(0);
Log.e("TestAR","trackingValuesVector is null");
}
}
}
}
loading 3d model:
private void loadModel()
{
if (mSurfaceView != null) {
mSurfaceView.queueEvent(new Runnable() {
#Override
public void run() {
File chairModel = AssetsManager.getAssetPathAsFile(getApplicationContext(),"chair.obj");
if (chairModel != null) {
mModel = metaioSDK.createGeometry(chairModel);
mModel.setScale(3f);
mModel.setTranslation(new Vector3d(0f,0f,-60f));
mGestureHandler.addObject(mModel, 1);
mModel.setRotation(new Rotation(0f, 0.5f, 0f));
mModel.setCoordinateSystemID(1);
}
}
});
}
else
{
Log.e("exception", "msurfaceview is null");
}
}
I see that you also tried setting the model to COS 0. This should actually work, if the tracking is lost.
If you do not see the model, you would have to play around with the scale value (i.e. set a low value like 0.01) and with the Z translation value. Set a negative Z value in order to move the model away from the camera clipping plane.

Spinner converter android

I am having some confusion with the spinner class in android. What I want to is make a converter, where the user picks a unit they want to convert, then in the second spinner pick the output unit. Ex Spinner 1: Yard² to Spinner 2: Feet². Im not sure how to set it up, so If yard² and feet² is selected then do this calculation. Here is the code I have so far:
private void UnitBegin_ItemSelected (object sender, AdapterView.ItemSelectedEventArgs e)
{
Spinner UnitBegin = (Spinner)sender;
string ubget = UnitBegin.SelectedItem.ToString();
if (ubget == "Yard²")
{
}
}
You can accomplish that by declaring private globar Spinners, like this:
private Spinner spinner1;
private Spinner spinner2;
// your code
// now just use the globally declared spinners (spinner1 and spinner2) in your code
private void UnitBegin_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e)
{
string selected1 = spinner1.SelectedItem.ToString();
string selected2 = spinner2.SelectedItem.ToString();
if(selected1.Equals("Yard²"))
{
if (selected2.Equals("m²"))
{
//do calculation
}
else if (selected2.Equals("unit²"))
{
//do calculation
}
else if (selected2.Equals("otherunit²"))
{
//do calculation
}
else
{
//ERROR
}
}
if (selected1.Equals("m²"))
{
if (selected2.Equals("Yard²"))
{
//do calculation
}
else if (selected2.Equals("unit²"))
{
//do calculation
}
else if (selected2.Equals("otherunit²"))
{
//do calculation
}
else
{
//ERROR
}
}
//repeat for all the possible units
}
But I would advise you to do something like this:
private Spinner spinner1;
private Spinner spinner2;
private float unit1;
private float unit2;
// your code
// now just use the globally declared spinners (spinner1 and spinner2) in your code
private void UnitBegin_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e)
{
string selected1 = spinner1.SelectedItem.ToString();
if(selected1.Equals("Yard²"))
{
unit1 = 0.5 //let's say this is the multiplier from Yard² to m² :)
}
//repeat for all the possible units
}
private void UnitEnd_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e)
{
string selected2 = spinner2.SelectedItem.ToString();
if(selected2.Equals("UNIT²"))
{
unit2 = 0.7 //let's say this is the multiplier from UNIT² to m² :)
}
//repeat for all the possible units
}
And in the method that calculates the result to display:
float result = value*unit1; //and you get the value in the "default" unit
float finalResult = result*unit2; //and you get the value converted to the final unit
return finalResult; //return the final converted value

Categories

Resources