Hi folks,
well ... first of all: I'm completely new to programming related to Android. I do have basic knowledge in programming with Basic and C. But im all new to Java and programming with the Android ecosystem (I am familiar with the Android ecosystem, though ... I've just never written code for Android).
Now I wanted a simple app to read out and display some sensor data, such as acceleration along y-axis and rotation angle around y-axis.
But I found the whole way you get stuff out of the sensors very confusing ans somehow unnecessarily complicated. However....
I've successfully managed to code an app, that checks whether certain sensors are available or not - and show an according text in a TextView for the user to read.
The next step was, I wanted to code an app that reads the rotation angle and shows the current angle in a TextView for the user. But I haven't managed that.
I found the whole System of reading the rotation data very complex..... why isn't there just a simple function like "get the y-axis rotation angle" and thats it .... I've searched a lot in the Interwebz, tried to understand how that stuff works, and used some code of some examples i thought i understood ... well, I obviously didn't ....
This is what I've got so far:
Code:
package test.sensor4;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
//float A[] = new float[9];
//float I[] = new float[9];
float[] mGravity;
float[] mGeomagnetic;
float azimut;
float pitch;
float roll;
Button btn1;
TextView tv1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
btn1 = (Button)findViewById(R.id.button1);
btn1.setOnClickListener(this);
//SensorManager.registerListener(this)
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
mGravity = event.values;
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD)
mGeomagnetic = event.values;
if (mGravity != null && mGeomagnetic != null) {
float A[] = new float[9];
float I[] = new float[9];
boolean success = SensorManager.getRotationMatrix(A, I, mGravity, mGeomagnetic);
if (success) {
float orientation[] = new float[3];
SensorManager.getOrientation(A, orientation);
azimut = orientation[0]; // orientation contains: azimut, pitch and roll
pitch = orientation[1];
roll = orientation[2];
TextView tv1 = (TextView)findViewById(R.id.text1);
tv1.setText(String.valueOf(+roll));
}
}
}
@Override
public void onClick(View e) {
TextView tv2 = (TextView)findViewById(R.id.text2);
tv2.setText(String.valueOf(+pitch));
}
}
what this does is: it doesn't change the text from the first textview at all ... in the second textview it prints "0.0"
I don't understand why .... Maybe you guys can help me.
Thanks in advance.
Best wishes.
Related
Hi guys,
I'm trying to develop an application that use the sensor light, when the light is less than a threshold the screen turn off.
I'm gained the light value but I've difficul to force the screen to turn off.
Someone can help me??
Code:
package com.example.screen_on_off;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.app.Activity;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private SensorManager mySensorManager;
private PowerManager mPowerManager;
private WindowManager mWindowManager;
private WakeLock mWakeLock;
TextView textLIGHT_available, textLIGHT_reading;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textLIGHT_available = (TextView)findViewById(R.id.LIGHT_available);
textLIGHT_reading = (TextView)findViewById(R.id.LIGHT_reading);
mySensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
mWindowManager.getDefaultDisplay();
Sensor LightSensor = mySensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(LightSensor != null){
textLIGHT_available.setText("Sensor.TYPE_LIGHT Available");
mySensorManager.registerListener(
LightSensorListener,
LightSensor,
SensorManager.SENSOR_DELAY_NORMAL);
}else{
textLIGHT_available.setText("Sensor.TYPE_LIGHT NOT Available");
}
}
private final SensorEventListener LightSensorListener = new SensorEventListener(){
[user=439709]@override[/user]
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
[user=1299008]@supp[/user]ressWarnings("deprecation")
[user=439709]@override[/user]
public void onSensorChanged(SensorEvent event) {
if(event.sensor.getType() == Sensor.TYPE_LIGHT){
textLIGHT_reading.setText("LIGHT: " + event.values[0]);
if (event.values[0]<250.00f) {
Toast.makeText(MainActivity.this,"The value is less than 250",Toast.LENGTH_LONG).show();
mPowerManager = (PowerManager) getSystemService(POWER_SERVICE);
mWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
mWakeLock.acquire();
}
//else mWakeLock.release();
}
}
};
}
Hi guys,
I'm trying to develop an application that use the sensor light, when the light is less than a threshold the screen turn off.
I'm gained the light value but I've difficult to force the screen to turn off
Someone can help me??
Code:
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.app.Activity;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private SensorManager mySensorManager;
private PowerManager mPowerManager;
private WindowManager mWindowManager;
private WakeLock mWakeLock;
TextView textLIGHT_available, textLIGHT_reading;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textLIGHT_available = (TextView)findViewById(R.id.LIGHT_available);
textLIGHT_reading = (TextView)findViewById(R.id.LIGHT_reading);
mySensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
mWindowManager.getDefaultDisplay();
Sensor LightSensor = mySensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(LightSensor != null){
textLIGHT_available.setText("Sensor.TYPE_LIGHT Available");
mySensorManager.registerListener(
LightSensorListener,
LightSensor,
SensorManager.SENSOR_DELAY_NORMAL);
}else{
textLIGHT_available.setText("Sensor.TYPE_LIGHT NOT Available");
}
}
private final SensorEventListener LightSensorListener = new SensorEventListener(){
[user=439709]@override[/user]
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
[user=1299008]@supp[/user]ressWarnings("deprecation")
[user=439709]@override[/user]
public void onSensorChanged(SensorEvent event) {
if(event.sensor.getType() == Sensor.TYPE_LIGHT){
textLIGHT_reading.setText("LIGHT: " + event.values[0]);
if (event.values[0]<250.00f) {
Toast.makeText(MainActivity.this,"The value is less than 250",Toast.LENGTH_LONG).show();
mPowerManager = (PowerManager) getSystemService(POWER_SERVICE);
mWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
mWakeLock.acquire();
}
//else mWakeLock.release();
}
}
};
}
I am having a problem with my first Android app. I am posting here looking for guidance to find a solution, or to decide if maybe what I am attempting is to bothersome for someone just learning the android platform. My Java and OO are very strong though.
I am writing a calculator app as my first android app.
I have a mode button on the calculator that changes the buttons to make new functions available.
When mode switches, certain buttons get changed to a different drawable with different colors, and all the text gets updated on all the buttons.
Each mode has a new string array corresponding to the text for that mode.
What I am currently trying to achieve is having a delay between the time that each button is updated, a sort of cascade effect. I have not successfully implemented this.
In the following code I have a toggleLabels method which attempts to do this. It has three if blocks corresponding to the three modes, which each gets a new set of text and buttons. There are two nested for loops in each running i=width and j=height.
To create the cascade effect I grabbed system time, and then subtracted from current time to see that 100ms had passed.
No cascade effect takes place, and when I hit the mode button, there is a long delay then all of the buttons switch at once. The delay seems to be exactly 2 seconds, which corresponds to the cumulative delay of 100ms per button X 20 buttons.
I also tried an alternate method of Thread.Sleep() which yielded the same result, and which I read was bad practice to implement in your UI thread.
Basically I am doing..
loop through each button
{
Change button drawable
Change button text
delay X time
}
But what is showing in the app is
loop through each button
{
Change button drawable
Change button text
}
delay (X * N buttons) amount of time
draw all the buttons at once
I
After doing a lot of investigating, and not finding to much relevant info out there, I am thinking I need to implement a new thread to do this in.
I also came up with the idea of extending a new class of button and overriding the ondraw method with a delay in it. Not sure this is a horribly improper way of doing it.
My code is as follows....
Code:
package com.example.calculator;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
public class MainActivity extends Activity {
EditText displayUpper;
EditText displayLower;
//View root;
LinearLayout keyPanel;
Button[][] buttons;
int width;
int height;
String[] labels1;
String[] labels2;
String[] labels3;
int mode;
long time;
boolean click;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
width=4;
height=5;
mode=3;
click=false;
// root = (LinearLayout)findViewById(R.id.root);
keyPanel = (LinearLayout)findViewById(R.id.keyPanel);
displayUpper = (EditText)findViewById(R.id.editText1);
displayLower = (EditText)findViewById(R.id.editText1);
labels1=getResources().getStringArray(R.array.first_panel);
labels2=getResources().getStringArray(R.array.second_panel);
labels3=getResources().getStringArray(R.array.third_panel);
assignButtons(); //<-must come before toggleLabel
toggleLabel(); //<-must come after assignButtons
final Runnable r = new Runnable()
{
public void run()
{
toggleLabel();
}
};
buttons[3][0].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
r.run();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
//---This method stores all the buttons in a multi-dimensional array
//--- Assigns buttons starting at left column from top to bottom
private void assignButtons()
{
buttons=new Button[width][height];
LinearLayout temp;
for(int i=0;i<width;i++)
{
temp = (LinearLayout)keyPanel.getChildAt(i);
for(int j=0;j<height;j++)
{
buttons[i][j] = (Button)temp.getChildAt(j);
}
}
}
//--This method set and toggles all the button labels
private void toggleLabel()
{
int pos=0;
boolean notchange=true;
if(mode==0)//<--If mode=0 change to second set of buttons
{
mode=1;
time=System.currentTimeMillis();
for(int i=0;i<width;i++)
{
for(int j=0;j<height;j++)
{
notchange=true;
while(notchange)
{
if(System.currentTimeMillis()-time>100)
{
notchange=false;
buttons[i][j].setText(labels2[pos]);
pos++;
if(i==3||j==0)
{
buttons[i][j].setBackgroundResource(R.drawable.sec_button);
}
time=System.currentTimeMillis();
}
}
}
}
}
else if(mode==1)//<--If mode=1 change to third set of buttons
{
mode=2;
time=System.currentTimeMillis();
for(int i=0;i<width;i++)
{
for(int j=0;j<height;j++)
{
notchange=true;
while(notchange)
{
if(System.currentTimeMillis()-time>100)
{
notchange=false;
buttons[i][j].setText(labels3[pos]);
pos++;
if(i==3||j==0)
{
buttons[i][j].setBackgroundResource(R.drawable.third_button);
}
time=System.currentTimeMillis();
}
}
}
}
}
else//<--else change back to first set of buttons
{
mode=0;
time=System.currentTimeMillis();
for(int i=0;i<width;i++)
{
for(int j=0;j<height;j++)
{
notchange=true;
while(notchange)
{
if(System.currentTimeMillis()-time>100)
{
notchange=false;
buttons[i][j].setText(labels1[pos]);
pos++;
if(i==3||j==0)
{
buttons[i][j].setBackgroundResource(R.drawable.calcbutton);
}
time=System.currentTimeMillis();
}
}
}
}
}
}
}
Does anyone have any input on this?
I do not really know how to finish this code?
All i want is to print whatever is entered within the editText to be listed in listview.
I am creating a dice game app, and within the xml part I have 1 edittext (in which you can type the name of the player), 1 button for adding another player. Basically every time some1 types in a name I want it to show up in the list once the button "add" is pressed. Likewise as more players are added the list should expand. Im using a lot of youtube examples, however simply do not know how to finish the code exactly.
Any help would be much appreciated
package nl.dut.ide.software.myapplication;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
public class LoginPage extends AppCompatActivity {
EditText typeplayers;
Button submitbutton;
ListView list;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_page);
typeplayers = (EditText)findViewById(R.id.edittext);
submitbutton = (Button)findViewById(R.id.Submitbutton);
list = (ListView)findViewById(R.id.list);
submitbutton.setOnClickListener(View.OnClickListener() {
@override
public void onClick (View, v){
String str = typeplayers.getText().toString();
list.add
}
}
}
}
Im following the steps laid out here for using the Settings Activity Template and despite some changes (e.g. now a root_preferences.xml file gets created instead of multiple xml files for different preference screens when selecting the Settings Activity template) I pretty much have nailed down the steps very similarly.
It says towards the end:
The first time you run the app, you should see "-1" displayed in the Toast because you haven't changed the setting yet.
Click to expand...
Click to collapse
However, instead of -1, Im seeing US as the toast message. Im thinking thats because its the default value, but they also set the default value as the US, yet the expectation according to the instructions is -1 the first time they run the app...how come?
Here is my code and the result Im getting first time running the app
SettingsActivity.java:
package com.example.droidcafe;
import android.os.Bundle;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.PreferenceFragmentCompat;
public class SettingsActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_activity);
if (savedInstanceState == null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.settings, new SettingsFragment())
.commit();
}
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
public static class SettingsFragment extends PreferenceFragmentCompat {
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.root_preferences, rootKey);
}
}
}
MainActivity.java:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent =
new Intent(MainActivity.this, OrderActivity.class);
intent.putExtra(EXTRA_MESSAGE, mOrderMessage);
startActivity(intent);
}
});
PreferenceManager.setDefaultValues(this,
R.xml.root_preferences, false);
SharedPreferences sharedPref = PreferenceManager
.getDefaultSharedPreferences(this);
String marketPref = sharedPref
.getString("market", "-1");
displayToast(marketPref);
}
root_preferences.xml
<PreferenceScreen xmlns:app="http://schemas.android.com/apk/res-auto">
<PreferenceCategory app:title="@string/pref_header_account">
<ListPreference
app:defaultValue="US"
app:entries="@array/pref_market_titles"
app:entryValues="@array/pref_market_values"
app:key="market"
app:negativeButtonText="@null"
app:positiveButtonText="@null"
app:title="@string/pref_title_account" />
</PreferenceCategory>
</PreferenceScreen>
strings.xml:
<string name="pref_header_account">Account</string>
<!-- Sync Preferences -->
<string name="pref_title_account">Market</string>
<string-array name="pref_market_titles">
<item>United States</item>
<item>Canada</item>
<item>United Kingdom</item>
<item>India</item>
<item>Japan</item>
<item>Other</item>
</string-array>
<string-array name="pref_market_values">
<item>US</item>
<item>CA</item>
<item>UK</item>
<item>IN</item>
<item>JA0</item>
<item>-1</item>
</string-array>
first time running app:
Expectation: -1
I realize the default value is US, but their codelab default is also US, yet the codelab says it should display first time -1.