What are my mistakes by using sensors? - sensors

I slowly make my first tries with using sensors. And i want to show the actual air pressure (My smartphone defently have a airpressuresensor.)
I look at some code and copy some code, and build the app. Now it doesnt work, and I dont know why. Does sensors need sth. in the manifest or so?
There are no errorcodes, just a applicationcrash...
the evil line seems to be, because if I build a try and catch around the app dont crash, but nothing happends. : sMgr.registerListener((SensorEventListener) this, sensor, SensorManager.SENSOR_DELAY_NORMAL);
Here is the code:
public class MainActivity extends ActionBarActivity {
public Handler handler = new Handler();
public double a;
SensorManager sMgr;
Sensor sensor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sMgr = (SensorManager)getSystemService(SENSOR_SERVICE);
List<Sensor> sensors = sMgr.getSensorList(Sensor.TYPE_PRESSURE);
if(sensors.size() > 0) {
sensor = sensors.get(0);
sMgr.registerListener((SensorEventListener) this, sensor, SensorManager.SENSOR_DELAY_NORMAL);
}
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public void onSensorChanged(SensorEvent event) {
float presure = event.values[0];
Log.d("PressureSens", ""+presure);
TextView textView = (TextView)findViewById(R.id.text);
textView.setText(""+ presure);
}

Related

How to add audio to Recycler View items

I'm making an app which will show different types of guitar and when the user will tap on the image(or text) of a particular type of guitar, it will play a riff of that type(eg. tapping on electric guitar will play an electric guitar riff). Here's my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_guitar_basics);
recGuitarTypes();
}
private void recGuitarTypes(){
recGtypes = (RecyclerView) findViewById(R.id.viewGuitarTypes);
GuitarTypesRecyclerViewAdapter adapter = new GuitarTypesRecyclerViewAdapter(this);
recGtypes.setAdapter(adapter);
recGtypes.setLayoutManager(new GridLayoutManager(this, 2));
ArrayList<Guitar> arrGuitar = new ArrayList<>();
arrGuitar.add(new Guitar("Nylon String Spanish", "https://inside-guitar.com/wp-content/uploads/2019/05/Savarez-Flamenco-Guitar-Strings.jpg"));
arrGuitar.add(new Guitar("Steel String Acoustic","https://hearthemusicplay.com/wp-content/uploads/2017/05/steelstringguitar-e1494992902529-1140x638.jpg"));
arrGuitar.add(new Guitar("Electric Guitar","https://cdn.mos.cms.futurecdn.net/papiVxAvWm3QaDAD8fSdqS-970-80.jpg.webp"));
adapter.setGuitars(arrGuitar);
}
I wanted to check if the code worked which is why I tried to test it using a single audio file in my "raw" folder applied to all the items in the RecyclerView. It didn't. Here's the code if you wanna check that out:
recGtypes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MediaPlayer mediaPlayer = MediaPlayer.create(view.getContext(), R.raw.steel_string);
mediaPlayer.start();
}
});
Thanks for your help in advance.
can you try below code ?
recGtypes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
private MediaPlayer mediaPlayer = new MediaPlayer();
AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.steel_string);
mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
file.close();
mediaPlayer.prepare();
mediaPlayer.start();
}
});

Android Studio OnSharedPreferenceChangedListener not working in MainActivity

I have a daily alarm and a settings page that allow users to change the timing that the daily alarm fires. I have a OnSharedPreferenceChangeListener in my SettingsFragment that extends PreferenceFragmentCompat and it is working here. However, when I do the same thing in my MainActivity, it does not seem to be working.
This is my code in Main Activity:
'''
public class MainActivity extends AppCompatActivity {
//some other variables
private SharedPreferences.OnSharedPreferenceChangeListener preferenceChangeListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//some other code
preferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals("daily alarm time")){
int alarmTime = sharedPreferences.getInt("daily alarm time", 36000000);
setdailyalarm(alarmTime, true, false);
System.out.println("onsharedpreferencechange activited");
}
if (key.equals("daily alarm toggle")){
Boolean dailyAlarmToggle = sharedPreferences.getBoolean(key, true);
System.out.println("111111111111111111111111");
if (dailyAlarmToggle){
int alarmTime = sharedPreferences.getInt(key, 36000000);
setdailyalarm(alarmTime, true, false);
}
else{
int alarmTime = sharedPreferences.getInt(key, 36000000);
setdailyalarm(alarmTime, true, true);
}
}
}
};
}
'''
This is my onpause and onresume:
'''
#Override
protected void onPause() {
super.onPause();
PreferenceManager.getDefaultSharedPreferences(this).unregisterOnSharedPreferenceChangeListener(preferenceChangeListener);
}
#Override
protected void onResume() {
super.onResume();
PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(preferenceChangeListener);
}
'''
When I start my app and check my System.out, '''System.out.println("onsharedpreferencechange activited");''' does not seem to be firing which means my OnSharedPreferenceChangeListener is not working. I have seem the other discussions SharedPreferences.onSharedPreferenceChangeListener not being called consistently but it does not seem to be the solution to my problem.
When I start my app and check my System.out, '''System.out.println("onsharedpreferencechange activited");''' does not seem to be firing which means my OnSharedPreferenceChangeListener is not working.
It's because you're always unregistering the listener in your onPause(). So, whenever you leave the activity, the listener is removed and you can't listen for the SharedPreferences changes.
You could register the listener inside your onCreate() method.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// setup the listener
preferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
...
// then register it
PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(preferenceChangeListener);
}
Then unregister the listener when you close the activity by overriding the onDestroy() method:
#Override
public void onDestroy() {
PreferenceManager.getDefaultSharedPreferences(this).unregisterOnSharedPreferenceChangeListener(preferenceChangeListener);
super.onDestroy();
}
Or unregister the listener whenever you call finish() method. Either call the unregister part before finish() or overriding the finish() method.

Converting a sensor value using simple arithmetic

I am currently working on a light sensor. I managed to make the sensor work. But I want to change the value of the sensor being shown by multiplying it with 0.002 with a press of a button. I can't seem to get the code of the button to multiply because it keeps saying operator (*) cannot be applied to java.lang.String, double. I have tried the double.parse but can't seems to get to work. Here is my code:
public class MainActivity extends AppCompatActivity implements SensorEventListener {
TextView textView;
SensorManager sensorManager;
Sensor sensor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
sensorManager = (SensorManager) getSystemService(Service.SENSOR_SERVICE);
sensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
Button button = (Button) findViewById(R.id.button3);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View multiply) {
textView.setText(Integer.parseInt(textView.getText().toString()*0.002));
}
});
}
#Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
#Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
public void onSensorChanged(SensorEvent sensorEvent) {
if (sensorEvent.sensor.getType() == Sensor.TYPE_LIGHT) {
textView.setText("" + sensorEvent.values[0]);
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int i) {
}

Counting number of times android app goes into background

I'm developing an app which counts number of times the app goes to the background. It also retains the values when the orientation is changed. Though I have it working of all use cases, I have one use case which does not work.
Case : When I press the home button, change the phone's orientation and reopen the app, It does open in landscape mode but, the background count does not increase.
I have tried setting values in all the life cycle methods. It doesn't work. Hope somebody can help me with this.
`
public class MainActivity extends AppCompatActivity {
private int clickCount =0, backgroundCount = 0;
TextView tvClickCountValue, tvBackgroundCountValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if( savedInstanceState != null){
clickCount = savedInstanceState.getInt("COUNT");
backgroundCount = savedInstanceState.getInt("BGCOUNT");
}
setContentView(R.layout.activity_main);
tvClickCountValue = (TextView) this.findViewById(R.id.tvClickCountValue);
tvBackgroundCountValue = (TextView) this.findViewById(R.id.tvBackgroundCountValue);
setView(MainActivity.this);
}
public void onClick(View v){
clickCount += 1;
tvClickCountValue.setText(Integer.toString(clickCount));
}
public void setView(Context ctx){
tvClickCountValue.setText(Integer.toString(clickCount));
tvBackgroundCountValue.setText(Integer.toString(backgroundCount));
}
#Override
protected void onStop() {
super.onStop();
backgroundCount += 1;
}
#Override
protected void onResume() {
super.onResume();
tvClickCountValue.setText(Integer.toString(clickCount));
tvBackgroundCountValue.setText(Integer.toString(backgroundCount));
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("COUNT", clickCount);
outState.putInt("BGCOUNT", backgroundCount);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
clickCount = savedInstanceState.getInt("COUNT");
backgroundCount = savedInstanceState.getInt("BGCOUNT");
}
}
This article contains useful information: https://developer.android.com/guide/topics/resources/runtime-changes.html especially in the section about Handling The Change.
Try handling it on onConfigurationChanged() of you have disabled Activity restarts on orientation changes. Otherwise, probably through this article you will find which case applies to your scenario.
By reading the problem description, I am assuming that if you don't rotate the device the application works as intended.
you need to persist the count in the SharedPreferences. each time you reopen the app read the last value from the SharedPreferences. And increment and save to SharedPreferences each time the app is hidden.
Then you can count the with #kiran code:
public class BaseActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
public static boolean isAppInFg = false;
public static boolean isScrInFg = false;
public static boolean isChangeScrFg = false;
#Override
protected void onStart() {
if (!isAppInFg) {
isAppInFg = true;
isChangeScrFg = false;
onAppStart();
}
else {
isChangeScrFg = true;
}
isScrInFg = true;
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
if (!isScrInFg || !isChangeScrFg) {
isAppInFg = false;
onAppPause();
}
isScrInFg = false;
}
public void onAppStart() {
// app in the foreground
// show the count here.
}
public void onAppPause() {
// app in the background
// start counting here.
}
}

If Statement Not Executed in AutocompleteTextView

I'm new to Android Studio and currently working on my first app. Thanks to numerous examples on here i have managed to catch up on the basics very quickly. I now have a problem with my autocompletetextview, i want to get the text selected then use it in a if statement to determine what is shown on the "results" textview. The if statement works fine but only for the "else" part and i can't figure out where i went wrong.
I have commented out the onItemClickListener because the "testfoodph" method does the same.
Here is the activity code:
public class phTester extends AppCompatActivity {
Intent intent = getIntent();
AutoCompleteTextView text;
MultiAutoCompleteTextView text1;
TextView results;
String foodies;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ph_tester);
String[] foods = getResources().getStringArray(R.array.foodlist);
text=(AutoCompleteTextView)findViewById(R.id.autoCompleteTextView);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,foods);
text.setAdapter(adapter);
text.setThreshold(1);
results=(TextView)findViewById(R.id.phResults);
foodies = text.getText().toString();
text.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//if (foodies.equalsIgnoreCase("Mango")) {
//results.setText(getString(R.string.phAlk));
}
//else {
//results.setText(getString(R.string.Error));
//}
//}
});
}
public void TestFoodPH(View view) {
if (foodies.equalsIgnoreCase("Mango")) {
results.setText(getString(R.string.phAlk));
}
else {
results.setText(getString(R.string.Error));
}
}

Resources