How to print values coming in logcat to UI of android? - java

I have created a proximity service which performs basic on/off of screen depending on the sensor value. I needed to time these sensor changes so i used the following code
override fun onSensorChanged(event: SensorEvent) {
val distance = event.values[0]
val max = event.sensor.maximumRange
val startTime = System.currentTimeMillis()
if (distance < Math.min(max, 8.toFloat())) {
listener.onNear()
} else {
listener.onFar()
}
val endTime = System.currentTimeMillis()
System.out.println("That took " + (endTime - startTime) + " milliseconds")
}
I am getting the values in log cat but i need to print these on my app, my app activity is in another java class called settings activity. I have added a textview called "Time taken" how to push those values of (endTime-startTime) to this textview??? or should i have to use any other layout comonent??
My settings layout image

You need to set id of that TextView and then bindview in java and after it you can set text into TextView
Your XML should have this widget
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
now in your java, bind this textview with id like
TextView tv=(TextView)findViewById(R.id.textView1);
now you have tv object of TextView that will help you to setText() like
tv.setText("That took " + (endTime - startTime) + " milliseconds");

make the variables you want to access public static
and then access them by
tv.setText(YourActivity.YourVariable);

Related

Can't make the app save variables when it exits

I am making an app where the user keeps pressing a button to get in-app money, my problem is whenever the app is closed or paused when i return the app's Money counter resets to zero. So i tried to make a Shared Preferences code to save my variables when the app pauses or stops, However when i resume the app the Counter doesn't reset to zero but as soon as i click on the button to generate money it resets to zero? Any help would be appreciated.
The Code being executed when the button is pressed:
myBalance += 1;
TextView balanceShow = findViewById(R.id.balanceShow);
balanceShow.setText("Balance: " + myBalance + "Coin");
And this is the code executed on the application exit event (The code that saves the user balance):
TextView balanceShow = findViewById(R.id.balanceShow);
String balance = balanceShow.getText().toString();
SharedPreferences data = getSharedPreferences("MySavedData", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = data.edit();
editor.putString("BALANCE", balance);
editor.commit();
Toast.makeText(this, "Saved!", Toast.LENGTH_SHORT).show();
And finally this is the code executed on the app's resume that loads the user's balance when he comes back:
TextView balanceShow = findViewById(R.id.balanceShow);
SharedPreferences data = getSharedPreferences("MySavedData", Context.MODE_PRIVATE);
String balance = data.getString("BALANCE", "No Data Found!");
balanceShow.setText(balance);
Toast.makeText(this, "Loaded!", Toast.LENGTH_SHORT).show();
To make things more clear:
1- The app starts with a "0" Coins balance.
2- I click on the button, to generate "1" Coin every time i press it which triggers the first code i posted.
3- Let's say i made "80" Coin.
4- Now i close the app.
5- I open the app, I find that my balance is "80" Coins. Great!
6- I press on the button, then the balance resets to "0" Coins and starts from scratch again!
Please help it's been hours since i am trying to figure what's happening, and i couldn't, What's wrong with the code? Also i tried numerous other saving codes and they all crash the app, this is the only Saving code that seems to work with me, Any help would be highly appreciated! Thanks!
TextView balanceShow = findViewById(R.id.balanceShow);
SharedPreferences data = getSharedPreferences("MySavedData", Context.MODE_PRIVATE);
String balance = data.getString("BALANCE", "No Data Found!");
balanceShow.setText(balance);
Toast.makeText(this, "Loaded!", Toast.LENGTH_SHORT).show();
Herein lies your problem. You are only updating the value of the TextField, whereas the value of the counter behind the TextField (here myBalance) is zero. Instead of saving the data stored in the TextField to SharedPreferences, you should instead store the integer data in the myBalance counter to the preferences and load that when you resume the app.
In short, in order to save coins:
private void saveCoinsToPreferences() {
SharedPreferences data = getSharedPreferences("MySavedData", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = data.edit();
editor.putInt("BALANCE", myBalance);
editor.commit();
Toast.makeText(this, "Saved!", Toast.LENGTH_SHORT).show();
}
And in order to retrieve coins:
private int retrieveCoins() {
TextView balanceShow = findViewById(R.id.balanceShow);
SharedPreferences data = getSharedPreferences("MySavedData", Context.MODE_PRIVATE);
myBalance = data.getInt("BALANCE", -1);
balanceShow.setText("Balance: " + myBalance + "Coin");
Toast.makeText(this, "Loaded!", Toast.LENGTH_SHORT).show();
}
Try this
private void saveCoins(Context context, String coin) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor spe = sp.edit();
spe.putString(context.getString(R.string.pref_coin), coin);
spe.apply();
}
to retrieve the coins
private String getPaymentSelected(Context c) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(c);
return sp.getString(c.getString(R.string.pref_coin), "0");
}
create a string variable pref_coin in strings.xml (inside values folder)

Firebase OnChildAdded() event is producing doubles in the scrollview

I just started to learn Firebase for android a couple of weeks ago, and now I am creating a very basic chat application.
My problem occurs when I press the home button and then go back to the app. I think it calls the OnChildAdded() event again, and so it produces doubles. I don't know how to fix this. I'll be grateful if anyone could help me out.
This is the part where I am having trouble:
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
//messageText.append(username + ": " + messageReceived + " \n");
Iterator iterator = dataSnapshot.getChildren().iterator();
String newmsg = null, theusername = null;
while (iterator.hasNext()){
newmsg = (String) ((DataSnapshot) iterator.next()).getValue();
theusername = (String) ((DataSnapshot) iterator.next()).getValue();
}
messageText.append(theusername + ": " + newmsg + " \n");
scrollView.postDelayed(new Runnable() {
#Override
public void run() {
scrollView.fullScroll(ScrollView.FOCUS_DOWN);
}
},200);
}
Here is a picture of the emulator and the structure of my firebase console:
If onChildAdded() is being called multiple times for the same child, it is very likely that you have multiple listeners attached. You'll need to detach the listener when your activity becomes inactive.
// if you attach like this
var listener = ref.addChildEventListener(childEventListener);
// later detach the listener with
ref.removeEventListener(listener);
The best place to detach the listener depends on where you attached it. It is usually best to think of the pairs: onCreate()->onDestroy(), onStart()->onStop(), onResume()->onPause().

Using sensor in android to detect a jump

First of all I am only getting started with android and java so please be indulgent.
So, i want to make a "jump" detector using the sensor in Android devices.
Basically i want to use the information returned by my sensor and compare it to detect if the user jumped or not.
Physics is pretty simple, I only need two very close value (a jump last for about a second) of the Y-axis and compare the average of these two values to a "limit value".
My main problem is I don't know how to get two differents values from my sensor.
I tried to use the System.currentTimeMillis() to catch a value at a very specific moment and compare it with a older or newer value, but it doesn't seem to work very well.
Here is my code.
public void onSensorChanged(SensorEvent event) {
acceleration.setText("X: " +event.values[0]+ " Y:" +event.values[1] + "Z: " +event.values[2] +"Nombre de sauts" +saut);
Yacc = event.values[1];
long curTime = System.currentTimeMillis();
long lastUpdate = curTime - 400;
if((curTime - lastUpdate)>390){
lastUpdate = curTime;
float moyY = (Yacc - last_Yacc)/2;
if(moyY > 5){
saut = saut +1;
}
compteur.setText("currenttime " +curTime + " lastUpdate "+ lastUpdate +" saut=" +saut + " Valeur moyenne" +moyY + " saut=" +saut);
}
last_Yacc = Yacc;
}
I thank you all in advance for you consideration.

Adjusting Volume in Android Audiomanager is inaccurate

in my Android Application i have a method, which allows me to adjust the volume. This works like it should.
public void adjustVolume(int adjustType){
if(myAudioManager == null) {
myAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
}
if (adjustType == 0){
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
Toast.makeText(getApplicationContext(), "mute audio", Toast.LENGTH_SHORT).show();
}
else if(adjustType == 1) {
myAudioManager.adjustVolume(AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI);
Toast.makeText(getApplicationContext(), "decrease volume", Toast.LENGTH_SHORT).show();
}
else if (adjustType == 2){
myAudioManager.adjustVolume(AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
Toast.makeText(getApplicationContext(), "increase volume", Toast.LENGTH_SHORT).show();
}
else if (adjustType == 3){
int maxVolume = myAudioManager.getStreamMaxVolume(AudioManager.STREAM_SYSTEM);
myAudioManager.setStreamVolume(AudioManager.STREAM_SYSTEM, maxVolume, AudioManager.FLAG_SHOW_UI);
Toast.makeText(getApplicationContext(), "Max volume", Toast.LENGTH_SHORT).show();
}
Log.d(LOG_TAG, "Volume is " + myAudioManager.getStreamVolume(AudioManager.STREAM_SYSTEM));
}
e.g. I can call adjustVolume(1) to decrease the volume, and adjustVolume(2) to increase the volume. From Volume zero, to max volume it takes 15 steps
So far, so good.
Now I have another method, where I want to set the volume directly:
public void adjustVolumeDirect(int volumeValue) {
if(myAudioManager == null) {
myAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
}
//maxVolume is 7
int maxVolume = myAudioManager.getStreamMaxVolume(AudioManager.STREAM_SYSTEM);
float factor = (float)volumeValue / 100;
int targetVolume = (int) (maxVolume * factor);
Log.d(LOG_TAG,"MAX_VOLUME = "+maxVolume+" VOLUMEVALUE = " +volumeValue+ " TARGET VOLUME = " + targetVolume + "factor = " + factor);
myAudioManager.setStreamVolume(AudioManager.STREAM_SYSTEM,targetVolume , AudioManager.FLAG_SHOW_UI);
}
e.g.
adjustVolumeDirect(100) should set the Volume to max. adjustVolumeDirect(50) should set in to 50% and so on.
And this part does not work like I expect it. I can only set the volume in 7 steps! The method above gives me 15 steps!
Can anyone give me a hint how to solve this?
I want to set the volume in 10-steps:
adjustVolumeDirect(10) = 10%
adjustVolumeDirect(20) = 20%
...
adjustVolumeDirect(100) = 100%
How can I achieve this?
The reason you have a different number of steps is probably because two different audio streams are affected - for example the system audio stream, which may have 7 steps and the media audio stream, which might have 15.
The number of steps are different for various android devices and are defined in the system. See also this issue in the android bug tracker.
There are different ways to allow a finer tuning depending on your device. You can probably find some more information here on the android stackexchange site.
I've resolved the issue with this:
mAudioManager.getStreamMaxVolume(audio.STREAM_MUSIC)**/3**
mAudioManager.getStreamMaxVolume(audio.STREAM_MUSIC)**/2**
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, audio.getStreamMaxVolume(mAudioManager.STREAM_MUSIC)/3, AudioManager.FLAG_SHOW_UI);

Java How to get the time when timer is stopped?

I'm currently referring to this link to create the timer for my program.
But I don't know how to get the time when timer is stopped.
I think System.getcurrentTimeMillis() cannot be used at this moment.
So, how can I get the current time when timer is stopped with the method mentioned?
EDIT :
I'm currently building a simple 4X4 memory game, and I have timer in my program, using the method from this link.
At the end of the game, I'll use a showMessageDialog to display the number of clicks and time used. However, I'm just able to display the clicks, which is the easiest part.
Based on the method from the link, I think I can use an easy way such as
JOptionPane.showMessageDialog( null, "Congratulations. \n You have win the game with " + click + " click(s) in " + hour + "hour(s) " + minute + " minute(s) " + second + " second(s).", "Win", 1);
Is there any better way of doing it?
You can use
Date d = new Date();
DateFormat df = new SimpleDateFormat("hh:mm:ss");
String dateStr = df.format(d);

Categories