activity stacking over existing activity - java

I got a little problem with my android app. It is an app to determine the steadiness of hand using accelerometer.I have two activities, Vert.java and Calcu.java. In Vert.java there is an animation function comprising of 25 png files. It also has the functions to retrieve the acceleromter values of x,y and z axes. A combined value is transferred to Calcu.java, where scores are given for specific range of values using if loop.But, while running the "Calcu" activity is reappearing. I am new to android. Please help.
These are my codes..
Vert.java
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
public class Vert extends Activity implements SensorEventListener{
Sensor accelerometer1;
SensorManager sm1;
float x1=0,y1=0,z1=0,tx1=0,ty1=0,tz1=0,oldx1=0,oldy1=0,oldz1=0,totalx1=0,totaly1=0,totalz1=0;
Intent m1;
int z;
ImageView img;
Timer timer;
Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
overridePendingTransition(R.anim.slide_in,R.anim.slide_out);
setContentView(R.layout.vert);
sm1=(SensorManager)getSystemService(SENSOR_SERVICE);
accelerometer1=sm1.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sm1.registerListener(this, accelerometer1,SensorManager.SENSOR_DELAY_NORMAL);
img=(ImageView)findViewById(R.id.ivAnim);
AnimationDrawable animation=new AnimationDrawable();
animation.addFrame(getResources().getDrawable(R.drawable.a),200);
animation.addFrame(getResources().getDrawable(R.drawable.b),200);
animation.addFrame(getResources().getDrawable(R.drawable.c),200);
animation.addFrame(getResources().getDrawable(R.drawable.d),200);
animation.addFrame(getResources().getDrawable(R.drawable.e),200);
animation.addFrame(getResources().getDrawable(R.drawable.f),200);
animation.addFrame(getResources().getDrawable(R.drawable.g),200);
animation.addFrame(getResources().getDrawable(R.drawable.h),200);
animation.addFrame(getResources().getDrawable(R.drawable.i),200);
animation.addFrame(getResources().getDrawable(R.drawable.j),200);
animation.addFrame(getResources().getDrawable(R.drawable.k),200);
animation.addFrame(getResources().getDrawable(R.drawable.l),200);
animation.addFrame(getResources().getDrawable(R.drawable.m),200);
animation.addFrame(getResources().getDrawable(R.drawable.n),200);
animation.addFrame(getResources().getDrawable(R.drawable.o),200);
animation.addFrame(getResources().getDrawable(R.drawable.p),200);
animation.addFrame(getResources().getDrawable(R.drawable.q),200);
animation.addFrame(getResources().getDrawable(R.drawable.r),200);
animation.addFrame(getResources().getDrawable(R.drawable.s),200);
animation.addFrame(getResources().getDrawable(R.drawable.t),200);
animation.addFrame(getResources().getDrawable(R.drawable.u),200);
animation.addFrame(getResources().getDrawable(R.drawable.v),200);
animation.addFrame(getResources().getDrawable(R.drawable.w),200);
animation.addFrame(getResources().getDrawable(R.drawable.x),200);
animation.addFrame(getResources().getDrawable(R.drawable.y),200);
animation.setOneShot(false);
img.setImageDrawable(animation);
animation.start();
}
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
x1=event.values[0];
y1=event.values[1];
z1=event.values[2];
timer=new Timer();
timer.scheduleAtFixedRate(new TimerTask(){
#Override
public void run() {
// TODO Auto-generated method stub
oldx1=x1;
oldy1=y1;
oldz1=z1;
}
}, 200, 200);
String str=String.valueOf(tx1);
m1=new Intent(Vert.this,Calcu.class);
m1.putExtra("score", str);
if(oldx1>x1){
totalx1=oldx1-x1;
}
else if(x1>oldx1){
totalx1=x1-oldx1;
}
if(oldy1>y1){
totaly1=oldy1-y1;
}
else if(y1>oldy1){
totaly1=y1-oldy1;
}
if(oldz1>z1){
totalz1=oldz1-z1;
}
else if(z1>oldz1){
totalz1=z1-oldz1;
}
tx1=tx1+(totalx1+totaly1+totalz1);
handler=new Handler();
handler.postDelayed(new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
startActivity(Vert.this.m1);
m1.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
finish();
}
},5000);
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
this.sm1.unregisterListener(this);
timer.cancel();
}
}
Vert.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/vertpageplain"
android:padding="20dp"
android:orientation="vertical" >
<TextView
android:id="#+id/tvVertHead"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:textSize="30dp"
android:textColor="#138808"
android:text="KEEP YOUR HANDS STEADY TILL THE BOTTLE GETS EMPTY..." />
<ImageView
android:id="#+id/ivAnim"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:src="#drawable/a" />
</LinearLayout>
Calcu.java
import java.io.ByteArrayOutputStream;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.TextView;
public class Calcu extends Activity{
float krip1;
double score1;
String sScore;
TextView finalScore1;
ImageButton bB1,bS1,bE1;
Bitmap b;
Intent intent,chooser;
Uri imageUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
overridePendingTransition(R.anim.slide_in,R.anim.slide_out);
setContentView(R.layout.result);
String pky1 = getIntent().getStringExtra("score");
krip1=Float.valueOf(pky1);
finalScore1=(TextView)findViewById(R.id.tvScore1);
bB1=(ImageButton)findViewById(R.id.bMain1);
bS1=(ImageButton)findViewById(R.id.bShare1);
bE1=(ImageButton)findViewById(R.id.bExit1);
bB1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent n=new Intent(Calcu.this,Play.class);
n.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
n.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(n);
}
});
bS1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(score1==10){
b=BitmapFactory.decodeResource(getResources(), R.drawable.scorea);
}
else if(score1==9.5){
b=BitmapFactory.decodeResource(getResources(), R.drawable.scoreb);
}
else if(score1==9){
b=BitmapFactory.decodeResource(getResources(), R.drawable.scorec);
}
else if(score1==8.5){
b=BitmapFactory.decodeResource(getResources(), R.drawable.scored);
}
else if(score1==8){
b=BitmapFactory.decodeResource(getResources(), R.drawable.scoree);
}
else if(score1==7.5){
b=BitmapFactory.decodeResource(getResources(), R.drawable.scoref);
}
else if(score1==7){
b=BitmapFactory.decodeResource(getResources(), R.drawable.scoreg);
}
else if(score1==6.5){
b=BitmapFactory.decodeResource(getResources(), R.drawable.scoreg);
}
else if(score1==6){
b=BitmapFactory.decodeResource(getResources(), R.drawable.scorei);
}
else if(score1==5.5){
b=BitmapFactory.decodeResource(getResources(), R.drawable.scorej);
}
else if(score1==5){
b=BitmapFactory.decodeResource(getResources(), R.drawable.scorek);
}
else if(score1==4.5){
b=BitmapFactory.decodeResource(getResources(), R.drawable.scorel);
}
else if(score1==4){
b=BitmapFactory.decodeResource(getResources(), R.drawable.scorem);
}
else if(score1==3.5){
b=BitmapFactory.decodeResource(getResources(), R.drawable.scoren);
}
else if(score1==3){
b=BitmapFactory.decodeResource(getResources(), R.drawable.scoreo);
}
else if(score1==2.5){
b=BitmapFactory.decodeResource(getResources(), R.drawable.scorep);
}
else if(score1==2){
b=BitmapFactory.decodeResource(getResources(), R.drawable.scoreq);
}
else if(score1==1.5){
b=BitmapFactory.decodeResource(getResources(), R.drawable.scorer);
}
else if(score1==1){
b=BitmapFactory.decodeResource(getResources(), R.drawable.scores);
}
else if(score1==0.5){
b=BitmapFactory.decodeResource(getResources(), R.drawable.scoret);
}
else if(score1==0){
b=BitmapFactory.decodeResource(getResources(), R.drawable.scoreu);
}
intent=new Intent(Intent.ACTION_SEND);
intent.setType("image/png");
ByteArrayOutputStream bytes=new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.PNG, 100, bytes);
String path=MediaStore.Images.Media.insertImage(getContentResolver(), b, "Title", null);
imageUri=Uri.parse(path);
intent.putExtra(Intent.EXTRA_TITLE, "SOBER SCORE CHALLENGE");
intent.putExtra(Intent.EXTRA_SUBJECT, "Sober score : "+score1+"What's your's?");
intent.putExtra(Intent.EXTRA_STREAM, imageUri);
intent.putExtra(Intent.EXTRA_TEXT, "This is beta version. The final version will soon be available in play store.");
chooser=Intent.createChooser(intent, "Share your Sober Score...");
startActivity(chooser);
}
});
bE1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent exit=new Intent(getApplicationContext(),MainActivity.class);
exit.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
exit.putExtra("EXIT", true);
startActivity(exit);
}
});
if(krip1<90){
score1=10;
}
else if(90<krip1 && krip1<100){
score1=9.5;
}
else if(100<krip1 && krip1<110){
score1=9;
}
else if(110<krip1 && krip1<135){
score1=8.5;
}
else if(135<krip1 && krip1<150){
score1=8;
}
else if(150<krip1 && krip1<160){
score1=7.5;
}
else if(160<krip1 && krip1<175){
score1=7;
}
else if(175<krip1 && krip1<185){
score1=6.5;
}
else if(185<krip1 && krip1<195){
score1=6;
}
else if(195<krip1 && krip1<210){
score1=5.5;
}
else if(210<krip1 && krip1<215){
score1=5;
}
else if(215<krip1 && krip1<225){
score1=4.5;
}
else if(225<krip1 && krip1<245){
score1=4;
}
else if(245<krip1 && krip1<265){
score1=3.5;
}
else if(265<krip1 && krip1<285){
score1=3;
}
else if(285<krip1 && krip1<305){
score1=2.5;
}
else if(305<krip1 && krip1<335){
score1=2;
}
else if(335<krip1 && krip1<365){
score1=1.5;
}
else if(365<krip1 && krip1<395){
score1=1;
}
else if(395<krip1 && krip1<425){
score1=0.5;
}
else if(krip1>425){
score1=0;
}
finalScore1.setText(""+score1+"");
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
Intent back=new Intent(Calcu.this,MainActivity.class);
back.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
back.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(back);
Calcu.this.finish();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
finish();
}
}
Result.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/resultpageplain"
android:orientation="vertical"
>
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:src="#drawable/sobercent" />
<TextView
android:id="#+id/tvScore1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:textSize="70dp"
android:textColor="#138808"
android:text="X" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<ImageButton
android:id="#+id/bMain1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="0dp"
android:layout_marginTop="30dp"
android:layout_marginLeft="30dp"
android:src="#drawable/bplayagain" />
<ImageButton
android:id="#+id/bShare1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="0dp"
android:layout_marginTop="30dp"
android:layout_marginLeft="50dp"
android:src="#drawable/bshare" />
</LinearLayout>
<ImageButton
android:id="#+id/bExit1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="0dp"
android:layout_gravity="center"
android:gravity="center"
android:src="#drawable/bexit" />
</LinearLayout>

Replace the below code snip it should work
#Override
public void run() {
// TODO Auto-generated method stub
startActivity(Vert.this.m1);
m1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
finish();
}

Related

Range seekbar to trim audio

I'm trying to incorporate somehow into Android audio player, functionality of marking of the fragment of the song in the player that it is supposed to play. I see this like clipping of the fragment as in Audacity. I'm trying to get it with a range seekbar (two blue dots on a line that can be adjust) on which user mark the beginning and the end to play and when replay mode is enabled the player will play that marked section over and over again.
This player looks like this
The application is written in the Java language.
Below are the related code.
Dependency
implementation 'com.yahoo.mobile.client.android.util.rangeseekbar:rangeseekbar-
library:0.1.0'
PlayerActivity.java
package com.example.marcin.playerexperiment;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;
import android.media.AudioAttributes;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import com.yahoo.mobile.client.android.util.rangeseekbar.RangeSeekBar;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class PlayerActivity extends AppCompatActivity {
RangeSeekBar<Integer> mRangeSeekBar;
MediaPlayer mMediaPlayer;
Button playButton, openButton, replayButton;
int max;
SeekBar mSeekBar;
public static final int PICK_FILE =99;
ScheduledExecutorService timer;
TextView title, elapse, mEndTextView;
String duration;
Boolean isRepeat = false;
Runnable mRunnable;
Handler mHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
//otwórz
openButton = findViewById(R.id.open);
//powtórz
replayButton = findViewById(R.id.replayButton);
//range seekbar
mRangeSeekBar = findViewById(R.id.rangeSeekBar);
//seekbar - linia dzwięku
mSeekBar = findViewById(R.id.seekBar);
//mRangeSeekBar.setNotifyWhileDragging(true);
title = (TextView) findViewById(R.id.title);
elapse = (TextView) findViewById(R.id.elapse);
playButton = findViewById(R.id.play);
// mEndTextView = findViewById(R.id.end_duration);
mHandler = new Handler();
//Odtwórz |>
playButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(mMediaPlayer != null){
if(mMediaPlayer.isPlaying()){
mMediaPlayer.pause();
playButton.setText("ODTWÓRZ");
timer.shutdown();
}else{
mMediaPlayer.start();
playButton.setText("PAUZA");
timer = Executors.newScheduledThreadPool(1);
timer.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
// playProgress ();
if (mMediaPlayer != null) {
if (!mSeekBar.isPressed()) {
mSeekBar.setProgress(mMediaPlayer.getCurrentPosition());
}
}
}
},10,10, TimeUnit.MILLISECONDS);
}
}
}
});
//otwieranie pliku dzwiękowego
openButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("audio/*");
startActivityForResult(intent, PICK_FILE);
}
});
mRangeSeekBar.setOnRangeSeekBarChangeListener(new RangeSeekBar.OnRangeSeekBarChangeListener<Integer>() {
#Override
public void onRangeSeekBarValuesChanged(RangeSeekBar<?> bar, Integer minValue, Integer maxValue) {
mMediaPlayer.seekTo(minValue);
max = maxValue;
String infoMax = String.valueOf(max);
Log.i("MAX", infoMax);
}
});
mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
if (mMediaPlayer != null){
int millis = mMediaPlayer.getCurrentPosition();
long total_secs = TimeUnit.SECONDS.convert(millis, TimeUnit.MILLISECONDS);
long mins = TimeUnit.MINUTES.convert(total_secs, TimeUnit.SECONDS);
long secs = total_secs - (mins*60);
elapse.setText(mins + ":" + secs + " / " + duration);
//Log.i("Duration:", duration);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
if (mMediaPlayer != null) {
mMediaPlayer.seekTo(seekBar.getProgress());
}
}
});
//Loop
replayButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//repeat = false
if(isRepeat){
isRepeat = false;
mMediaPlayer.setLooping(false);
replayButton.setText("Powtórka wyłączona");
Toast.makeText(PlayerActivity.this, "Tryb powtórki jest wyłączony", Toast.LENGTH_SHORT).show();
}else{
isRepeat = true;
mMediaPlayer.setLooping(true);
replayButton.setText("Powtórka włączona");
Toast.makeText(PlayerActivity.this, "Tryb powtórki jest włączony", Toast.LENGTH_SHORT).show();
}
//mediaPlayer.setLooping(true);
// Toast.makeText(PlayerActivity.this, "Repeat if ON", Toast.LENGTH_SHORT).show();
}
});
playButton.setEnabled(false);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_FILE && resultCode == RESULT_OK){
if (data != null){
Uri uri = data.getData();
createMediaPlayer(uri);
}
}
}
public void createMediaPlayer(Uri uri){
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setAudioAttributes(
new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.setUsage(AudioAttributes.USAGE_MEDIA)
.build()
);
try {
mMediaPlayer.setDataSource(getApplicationContext(), uri);
mMediaPlayer.prepare();
title.setText(getNameFromUri(uri));
playButton.setEnabled(true);
mRangeSeekBar.setNotifyWhileDragging(true);
mRangeSeekBar.setRangeValues(0, mMediaPlayer.getDuration());
max = mMediaPlayer.getDuration();
mSeekBar.setMax(max);
mSeekBar.setProgress(0);
long total_secs = TimeUnit.SECONDS.convert(max, TimeUnit.MILLISECONDS);
long mins = TimeUnit.MINUTES.convert(total_secs, TimeUnit.SECONDS);
long secs = total_secs - (mins*60);
duration = mins + ":" + secs;
elapse.setText("00:00 / " + duration);
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
releaseMediaPlayer();
}
});
} catch (IOException e){
title.setText(e.toString());
}
}
#SuppressLint("Range")
public String getNameFromUri(Uri uri){
String fileName = "";
Cursor cursor = null;
cursor = getContentResolver().query(uri, new String[]{
MediaStore.Images.ImageColumns.DISPLAY_NAME
}, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
fileName = cursor.getString(cursor.getColumnIndex(MediaStore.Images.ImageColumns.DISPLAY_NAME));
}
if (cursor != null) {
cursor.close();
}
return fileName;
}
private void playProgress () {
if (mMediaPlayer.getCurrentPosition() == max) {
mMediaPlayer.stop();
}
if (mMediaPlayer.isPlaying()) {
mRunnable = new Runnable() {
#Override
public void run() {
playProgress();
}
};
mHandler.postDelayed(mRunnable, 0);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
releaseMediaPlayer();
}
public void releaseMediaPlayer(){
if (timer != null) {
timer.shutdown();
}
if (mMediaPlayer != null) {
mMediaPlayer.release();
mMediaPlayer = null;
}
playButton.setEnabled(false);
elapse.setText("TYTUL");
elapse.setText("00:00 / 00:00");
mSeekBar.setMax(100);
mSeekBar.setProgress(0);
}
}
Activity_player.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".PlayerActivity">
<Button
android:id="#+id/play"
android:layout_width="wrap_content"
android:layout_height="37dp"
android:layout_marginStart="150dp"
android:layout_marginEnd="173dp"
android:text="Play"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/seekBar" />
<com.yahoo.mobile.client.android.util.rangeseekbar.RangeSeekBar
android:id="#+id/rangeSeekBar"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="357dp"
android:layout_marginBottom="20dp"
app:layout_constraintBottom_toTopOf="#+id/seekBar"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/elapse"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="287dp"
android:layout_marginBottom="51dp"
android:text="00-00"
app:layout_constraintBottom_toTopOf="#+id/rangeSeekBar"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.461"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0" />
<SeekBar
android:id="#+id/seekBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/rangeSeekBar" />
<androidx.constraintlayout.widget.Barrier
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:barrierDirection="top"
tools:layout_editor_absoluteX="92dp"
tools:layout_editor_absoluteY="357dp" />
<Button
android:id="#+id/open"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="154dp"
android:layout_marginEnd="163dp"
android:layout_marginBottom="140dp"
android:backgroundTint="#color/teal_200"
android:text="Open file"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/play" />
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="173dp"
android:layout_marginEnd="202dp"
app:layout_constraintBottom_toTopOf="#+id/elapse"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.824" />
<Button
android:id="#+id/replayButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="150dp"
android:layout_marginEnd="142dp"
android:backgroundTint="#color/purple_500"
android:text="Replay"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/open" />
</androidx.constraintlayout.widget.ConstraintLayout>

Android to Arduino via Bluetooth. App won't send string

I found some code in the Internet and changed it. I try to send a short string via Bluetooth. I use the HC-05 Bluetooth module.
I can connect my android device with the module but I can't send a string to my Arduino.
I have:
1 EditText to enter my string.
2 Buttons:
-1 to send
-2 to connect
Could you look over my code? Thank you:)
Android Code...
private BluetoothDevice device;
private BluetoothSocket socket;
private OutputStream outputStream;
String command;//string variable that will store value to be transmitted to the bluetooth module
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button BtSend = findViewById(R.id.BtSend);
Button BtVerbinden = findViewById(R.id.BtVerbinden);
final EditText EtEingabe = findViewById(R.id.EtEingabe);
BtSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
command = EtEingabe.getText().toString();
try {
outputStream.write(command.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
});
//Button that connects the device to the bluetooth module when pressed
BtVerbinden.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (BTinit()) {
BTconnect();
}
}
});
}
public boolean BTinit() {
boolean found = false;
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) //Checks if the device supports bluetooth
{
Toast.makeText(getApplicationContext(), "Device doesn't support bluetooth", Toast.LENGTH_SHORT).show();
}
if (!bluetoothAdapter.isEnabled())
{
Intent enableAdapter = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableAdapter, 0);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();
if (bondedDevices.isEmpty())
{
Toast.makeText(getApplicationContext(), "Please pair the device first", Toast.LENGTH_SHORT).show();
} else {
for (BluetoothDevice iterator : bondedDevices) {
if (iterator.getAddress().equals(DEVICE_ADDRESS)) {
device = iterator;
found = true;
break;
}
}
}
return found;
}
public boolean BTconnect() {
boolean connected = true;
try {
socket = device.createRfcommSocketToServiceRecord(PORT_UUID); //Creates a socket to handle the outgoing connection
socket.connect();
Toast.makeText(getApplicationContext(),
"Connection to bluetooth device successful", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
connected = false;
}
if (connected) {
try {
outputStream = socket.getOutputStream(); //gets the output stream of the socket
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream == null) {
try {
outputStream = socket.getOutputStream();
} catch (IOException e) {
}
}
return connected;
}
#Override
protected void onStart() {
super.onStart();
}
}
Android XML...
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.swini.gimbalarduino.MainActivity">
<Button
android:id="#+id/BtSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="184dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:text="Send"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<EditText
android:id="#+id/EtEingabe"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="220dp"
android:ems="10"
android:hint="Hoi"
android:inputType="textPersonName"
android:text="Text"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.503"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/BtVerbinden"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="Connect"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
Try to use this code but this code run in Fragment so carefully change the Code according to your activity.
package com.example.rishabhrawat.tablayoutapp;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.Image;
import android.os.AsyncTask;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Set;
import java.util.UUID;
import static android.app.Activity.RESULT_OK;
/**
* Created by Rishabh Rawat on 6/18/2017.
*/
public class OfflineVideo extends android.support.v4.app.Fragment {
Button f,r,l,b,s,dis;
ListView listView;
ImageView mic;
BluetoothAdapter adapter;
private Set<BluetoothDevice> paireddevices;
private String address;
BluetoothSocket btSocket = null;
private boolean isBtConnected = false;
private ProgressDialog progress;
private final int REQ_CODE_SPEECH_INPUT = 100;
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.offlinevideo,container,false);
f=(Button)view.findViewById(R.id.forward);
r=(Button)view.findViewById(R.id.right);
l=(Button)view.findViewById(R.id.left);
b=(Button)view.findViewById(R.id.backward);
s=(Button)view.findViewById(R.id.stop);
dis=(Button)view.findViewById(R.id.discover);
mic=(ImageView)view.findViewById(R.id.mic);
listView=(ListView)view.findViewById(R.id.listview);
f.setEnabled(false);
r.setEnabled(false);
l.setEnabled(false);
b.setEnabled(false);
s.setEnabled(false);
mic.setEnabled(false);
adapter=BluetoothAdapter.getDefaultAdapter();
dis.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ShowPairedDevices();
}
});
f.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
forward();
}
});
r.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
right();
}
});
l.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
left();
}
});
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
backward();
}
});
s.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stop();
}
});
mic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
VoiceInput();
}
});
return view;
}
public void ShowPairedDevices()
{
paireddevices=adapter.getBondedDevices();
ArrayList list = new ArrayList();
if (paireddevices.size()>0)
{
for(BluetoothDevice bt : paireddevices)
{
list.add(bt.getName() + "\n" + bt.getAddress());
}
}
else
{
Toast.makeText(getContext(), "No Paired Bluetooth Devices Found.", Toast.LENGTH_LONG).show();
}
final ArrayAdapter adapter=new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, list);
listView.setAdapter(adapter);
listView.setOnItemClickListener(myclicklistner);
}
private AdapterView.OnItemClickListener myclicklistner= new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> av, View v, int pos, long id) {
String info = ((TextView) v).getText().toString();
address = info.substring(info.length() - 17);
new connectbt().execute();
}
};
private class connectbt extends AsyncTask<Void, Void, Void> // UI thread
{
private boolean ConnectSuccess = true; //if it's here, it's almost connected
#Override
protected void onPreExecute()
{
progress = ProgressDialog.show(getActivity(), "Connecting...", "Please wait!!!"); //show a progress dialog
}
#Override
protected Void doInBackground(Void... devices) //while the progress dialog is shown, the connection is done in background
{
try
{
if (btSocket == null || !isBtConnected)
{
adapter = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device
BluetoothDevice dispositivo = adapter.getRemoteDevice(address);//connects to the device's address and checks if it's available
btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
btSocket.connect();//start connection
}
}
catch (IOException e)
{
ConnectSuccess = false;//if the try failed, you can check the exception here
}
return null;
}
#Override
protected void onPostExecute(Void result) //after the doInBackground, it checks if everything went fine
{
super.onPostExecute(result);
if (!ConnectSuccess)
{
Toast.makeText(getActivity().getApplicationContext(),"Connection Failed Please Try again later",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getActivity().getApplicationContext(), "Successfully Connected ", Toast.LENGTH_SHORT).show();
f.setEnabled(true);
r.setEnabled(true);
l.setEnabled(true);
b.setEnabled(true);
s.setEnabled(true);
mic.setEnabled(true);
isBtConnected = true;
}
progress.dismiss();
}
}
public void toast(String message)
{
Toast.makeText(getActivity().getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
private void forward()
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("F".toString().getBytes());
}
catch (IOException e)
{
toast("Error");
}
}
}
private void left()
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("L".toString().getBytes());
}
catch (IOException e)
{
toast("Error");
}
}
}
private void right()
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("R".toString().getBytes());
}
catch (IOException e)
{
toast("Error");
}
}
}
private void backward()
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("B".toString().getBytes());
}
catch (IOException e)
{
toast("Error");
}
}
}
private void stop()
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("S".toString().getBytes());
}
catch (IOException e)
{
toast("Error");
}
}
}
public void VoiceInput()
{
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
"Speak Command for Robot");
try {
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==REQ_CODE_SPEECH_INPUT)
{
if(resultCode==RESULT_OK)
{
ArrayList<String> result = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if(result.get(0).equals("forward"))
{
forward();
}
else if(result.get(0).equals("backward"))
{
backward();
}
else if(result.get(0).equals("stop"))
{
stop();
}
else if(result.get(0).equals("left"))
{
left();
}
else if(result.get(0).equals("right"))
{
right();
}
else
{
Toast.makeText(getActivity(), result.get(0), Toast.LENGTH_SHORT).show();
}
}
}
}
}
Layout File
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/forward"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Forward"
android:background="#00bfff"
android:textColor="#fff"
android:layout_above="#+id/stop"
android:layout_alignStart="#+id/stop"
android:layout_marginBottom="27dp" />
<Button
android:id="#+id/backward"
android:background="#00bfff"
android:textColor="#fff"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/forward"
android:layout_centerVertical="true"
android:text="Backward"
/>
<Button
android:id="#+id/left"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="24dp"
android:layout_marginEnd="14dp"
android:text="Left"
android:background="#00bfff"
android:textColor="#fff"
android:layout_above="#+id/backward"
android:layout_alignParentEnd="true" />
<Button
android:id="#+id/right"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:background="#00bfff"
android:textColor="#fff"
android:layout_alignTop="#+id/left"
android:layout_marginStart="17dp"
android:text="Right" />
<Button
android:id="#+id/stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="STOP"
android:background="#d22d2d"
android:textColor="#fff"
android:layout_alignBaseline="#+id/right"
android:layout_alignBottom="#+id/right"
android:layout_centerHorizontal="true" />
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/backward"
android:divider="#52f202"
android:dividerHeight="1dp"
android:id="#+id/listview"
android:layout_centerHorizontal="true"
android:layout_marginTop="48dp" />
<Button
android:id="#+id/discover"
android:background="#80ff00"
android:textSize="25dp"
android:textColor="#000099"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:fontFamily="sans-serif-smallcaps"
android:text="Discovery"
android:textAppearance="#style/TextAppearance.AppCompat.Light.Widget.PopupMenu.Large" />
<ImageView
android:id="#+id/mic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_below="#+id/discover"
app:srcCompat="#drawable/microphone" />
</RelativeLayout>
Arduino Code
char myserial;
void setup()
{
pinMode(11,OUTPUT);
pinMode(10,OUTPUT);
pinMode(9,OUTPUT);
pinMode(8,OUTPUT);
Serial.begin(9600);
}
void loop()
{
myserial=Serial.read();
switch(myserial)
{
case 'S':
digitalWrite(11,LOW);
digitalWrite(10,LOW);
digitalWrite(9,LOW);
digitalWrite(8,LOW);
break;
case 'B':
digitalWrite(11,HIGH);
digitalWrite(10,LOW);
digitalWrite(9,HIGH);
digitalWrite(8,LOW);
break;
case 'F':
digitalWrite(11,LOW);
digitalWrite(10,HIGH);
digitalWrite(9,LOW);
digitalWrite(8,HIGH);
break;
case 'L':
digitalWrite(11,HIGH);
digitalWrite(10,LOW);
digitalWrite(9,LOW);
digitalWrite(8,HIGH);
break;
case 'R':
digitalWrite(11,LOW);
digitalWrite(10,HIGH);
digitalWrite(9,HIGH);
digitalWrite(8,LOW);
break;
}
}
btSocket.getOutputStream().write(sendText.getText().toString().getBytes());
.

How to use if else statements on broadcast receiver? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
Hello I would like to ask for help on how to get the if else statements found below inside a onreceive from a broadcastreceiver . Im trying to change the button background depending on the value received. like when I receive the value 1 the button image will change to onn . Because it does not work when I place if else statements, but if I place the btn.setBackgroundResource(R.drawable.onn); before the if else statements it works fine however it defeats the purpose of having the app show which button is at on state. I'm trying to create an app that will update 6 switches depending on the text message. Like if I receive 111000 the first three switches will change image to on. TIA
Main activity
package com.example.asd;
import java.lang.reflect.Array;
import java.text.BreakIterator;
import android.R.array;
import android.R.layout;
import android.R.string;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.widget.TextView;
public class MainActivity extends Activity {
String[] bin={"0","0","0","0","0","0"};
String[] bin1={"0","0","0","0","0","0"};
Button zero,one,two,three,four,five,update,refresh;
IntentFilter intentFilter;
TextView tv1;
private final BroadcastReceiver intentReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//---display the SMS received in the TextView---
init();
zero=(Button)findViewById(R.id.one);
bin[0]=intent.getStringExtra("zero");
if (bin[0]!=null && bin[0].equalsIgnoreCase("1")) {
zero.setBackgroundResource(R.drawable.onn);
}
else {
zero.setBackgroundResource(R.drawable.off);
}
one=(Button)findViewById(R.id.two);
bin[1]=intent.getStringExtra("one");
if (bin[1]!=null && bin[1].equalsIgnoreCase("1")) {
one.setBackgroundResource(R.drawable.onn);
}
else {
one.setBackgroundResource(R.drawable.off);
}
two=(Button)findViewById(R.id.three);
bin[2]=intent.getStringExtra("two");
if (bin[2]!=null && bin[2].equalsIgnoreCase("1")) {
two.setBackgroundResource(R.drawable.onn);
}
else {
two.setBackgroundResource(R.drawable.off);
}
three=(Button)findViewById(R.id.four);
bin[3]=intent.getStringExtra("three");
if (bin[3]!=null && bin[3].equalsIgnoreCase("1")) {
three.setBackgroundResource(R.drawable.onn);
}
else {
three.setBackgroundResource(R.drawable.off);
}
four=(Button)findViewById(R.id.five);
bin[4]=intent.getStringExtra("four");
if (bin[4]!=null && bin[4].equalsIgnoreCase("1")) {
four.setBackgroundResource(R.drawable.onn);
}
else {
four.setBackgroundResource(R.drawable.off);
}
five=(Button)findViewById(R.id.six);
bin[5]=intent.getStringExtra("five");
if (bin[5]!=null && bin[5].equalsIgnoreCase("1")) {
five.setBackgroundResource(R.drawable.onn);
}
else {
five.setBackgroundResource(R.drawable.off);
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//---intent to filter for SMS messages received---
intentFilter = new IntentFilter();
zero=(Button)findViewById(R.id.one);
one=(Button)findViewById(R.id.two);
two=(Button)findViewById(R.id.three);
three=(Button)findViewById(R.id.four);
four=(Button)findViewById(R.id.five);
five=(Button)findViewById(R.id.six);
refresh=(Button)findViewById(R.id.refresh);
update=(Button)findViewById(R.id.update);
intentFilter.addAction("SMS_RECEIVED_ACTION");
zero.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (bin[0]=="1") {
bin[0]="0";
updateBtn();
}
else {
bin[0]="1";
updateBtn();
}
}
});
one.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (bin[1].equals("1")) {
bin[1]="0";
updateBtn();
}
else {
bin[1]="1";
updateBtn();
}
}
});
two.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (bin[2].equals("1")) {
bin[2]="0";
updateBtn();
}
else {
bin[2]="1";
updateBtn();
}
}
});
three.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (bin[3].equals("1")) {
bin[3]="0";
updateBtn();
}
else {
bin[3]="1";
updateBtn();
}
}
});
four.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (bin[4].equals("1")) {
bin[4]="0";
updateBtn();
}
else {
bin[4]="1";
updateBtn();
}
}
});
five.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (bin[5].equals("1")) {
bin[5]="0";
updateBtn();
}
else {
bin[5]="1";
updateBtn();
}
}
});
refresh.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
updateBtn();
String s="";
for (int i = 0; i < 6; i++) {
s+= bin[i];
}
String upToNCharacters = s.substring(0, Math.min(s.length(), 6));
Toast.makeText(getBaseContext(),upToNCharacters+"00", Toast.LENGTH_LONG).show();
s="";
}
});
update.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
updateBtn();
//Toast.makeText(getBaseContext(),s0+s1+s2+s3+s4+s5+"00", Toast.LENGTH_LONG).show();
Toast.makeText(getBaseContext(),bin[0]+bin[1]+bin[2]+bin[3]+bin[4]+bin[5]+"00", Toast.LENGTH_LONG).show();
}
});
}
private void updateBtn() {
for (int i = 0; i < 6; i++) {
if (bin[i]==null) {
bin[i]="0";
}
else
{
bin[i]=bin[i];
}
}
if (bin[0]=="1") {
zero.setBackgroundResource(R.drawable.onn);
}
else if(bin[0]=="0"){
zero.setBackgroundResource(R.drawable.off);
}
if (bin[1]=="1") {
one.setBackgroundResource(R.drawable.onn);
}
else if(bin[1]=="0"){
one.setBackgroundResource(R.drawable.off);
}
if (bin[2]=="1") {
two.setBackgroundResource(R.drawable.onn);
}
else if(bin[2]=="0"){
two.setBackgroundResource(R.drawable.off);
}
if (bin[3]=="1") {
three.setBackgroundResource(R.drawable.onn);
}
else if(bin[3]=="0"){
three.setBackgroundResource(R.drawable.off);
}
if (bin[4]=="1") {
four.setBackgroundResource(R.drawable.onn);
}
else if(bin[4]=="0"){
four.setBackgroundResource(R.drawable.off);
}
if (bin[5]=="1") {
five.setBackgroundResource(R.drawable.onn);
}
else if(bin[5]=="0"){
five.setBackgroundResource(R.drawable.off);
}
}
private void init() {
// TODO Auto-generated method stub
for (int i = 0; i < 6; i++) {
bin[i]="0";
}
}
#Override
protected void onResume() {
//---register the receiver---
registerReceiver(intentReceiver, intentFilter);
super.onResume();
}
#Override
protected void onPause() {
//---unregister the receiver---
unregisterReceiver(intentReceiver);
super.onPause();
}
}
activity xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/back"
tools:context="${relativePackage}.${activityClass}" >
<Button
android:id="#+id/one"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:background="#drawable/off"
android:rotation="90" />
<Button
android:id="#+id/two"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_below="#+id/one"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:background="#drawable/off"
android:rotation="90" />
<Button
android:id="#+id/three"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_below="#+id/two"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:background="#drawable/off"
android:rotation="90" />
<Button
android:id="#+id/four"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_below="#+id/three"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:background="#drawable/off"
android:rotation="90" />
<Button
android:id="#+id/five"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_below="#+id/four"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:background="#drawable/off"
android:rotation="90" />
<Button
android:id="#+id/six"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_below="#+id/five"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:background="#drawable/off"
android:rotation="90" />
<Button
android:id="#+id/refresh"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="19dp"
android:layout_marginLeft="31dp"
android:background="#drawable/button" />
<Button
android:id="#+id/update"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="69dp"
android:layout_marginLeft="31dp"
android:background="#drawable/button" />
</RelativeLayout>
Smsreceiver
package com.example.asd;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;
public class SMSReceiver extends BroadcastReceiver
{
#SuppressWarnings("deprecation")
#Override
public void onReceive(Context context, Intent intent)
{
//---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
String[] bin=new String[6];
if (bundle != null)
{
//---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
str += msgs[i].getMessageBody().toString();
bin[i]=msgs[i].getMessageBody().toString();
}
//---send a broadcast intent to update the SMS received in the activity---
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("SMS_RECEIVED_ACTION");
broadcastIntent.putExtra("zero", bin[0]);
broadcastIntent.putExtra("one", bin[1]);
broadcastIntent.putExtra("two", bin[2]);
broadcastIntent.putExtra("three", bin[3]);
broadcastIntent.putExtra("four", bin[4]);
broadcastIntent.putExtra("five", bin[5]);
broadcastIntent.putExtra("sms", str);
context.sendBroadcast(broadcastIntent);
}
}
}
You have to use
if (bin[0].equals("1")) {
zero.setBackgroundResource(R.drawable.onn);
}
else {
zero.setBackgroundResource(R.drawable.off);
}
because Strings will be compared with equals() method, not with ==
Also, You have to be sure that this String is not null if You get it from an intent. Like:
bin[0]=intent.getStringExtra("zero");
if(bin[0]!=null){
//Your if/else statements
}
Don't use == to compare String. You have to use equals or equalsIgnoreCase for compare String see developer doc for String and code looks like
if (bin[0]!=null && bin[0].equalsIgnoreCase("1")) {
zero.setBackgroundResource(R.drawable.onn);
}
else {
zero.setBackgroundResource(R.drawable.off);
}

How to toggle flashlight mode?

I want to add a button (which I have included in my activity_main) to my app that will launch a strobe effect when pressed and will stop when pressed again. I do not care about the speed, just that it toggles flash_mode_torch and flash_mode_off repeatedly until the button is pressed again.
I have tried:
Using a handler
Creating a separate class
The separate class containing the handler did not work because there was no intent in the main activity to launch or in the manifest because the code for it is not finished because I want to ask here how its done in the most simplest manner possible.
StrobeLightConfig.java
import android.app.Activity;
import android.content.Intent;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class StrobeLightConfig extends Activity {
boolean check = false;
Camera sandy;
StrobeRunner runner;
Thread bw;
ImageButton btnClick;
public final Handler mHandler = new Handler();
public final Runnable mShowToastRunnable = new Runnable() {
public void run() {
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnClick = (ImageButton) findViewById(R.id.btnSwitch);
runner = StrobeRunner.getInstance();
runner.controller = this;
if (runner.isRunning) {
} else {
try {
sandy = Camera.open();
if (sandy == null) {
return;
}
sandy.release();
} catch (RuntimeException ex) {
return;
}
}
bw = new Thread(runner);
bw.start();
btnClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (check) {
bw = new Thread(runner);
bw.start();
check = false;
} else {
check = true;
runner.requestStop = true;
}
}
});
final SeekBar skbar = (SeekBar) findViewById(R.id.SeekBar01);
skbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
runner.delay = 101 - progress;
runner.delayoff = 101 - progress;
}
});
}
#Override
protected void onStop() {
// runner.requestStop = true;
super.onStop();
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
// super.onBackPressed();
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startActivity(startMain);
}
}
StrobeRunner.java
import android.hardware.Camera;
public class StrobeRunner implements Runnable {
protected StrobeRunner()
{
}
public static StrobeRunner getInstance()
{
return ( instance == null ? instance = new StrobeRunner() : instance );
}
private static StrobeRunner instance;
public volatile boolean requestStop = false;
public volatile boolean isRunning = false;
public volatile int delay = 10;
public volatile int delayoff = 500;
public volatile StrobeLightConfig controller;
public volatile String errorMessage = "";
#Override
public void run() {
if(isRunning)
return;
requestStop=false;
isRunning = true;
Camera cam = Camera.open();
Camera.Parameters pon = cam.getParameters(), poff = cam.getParameters();
pon.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
poff.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
while(!requestStop)
{
try{
cam.setParameters(pon);
Thread.sleep(delay);
cam.setParameters(poff);
Thread.sleep(delayoff);
}
catch(InterruptedException ex)
{
}
catch(RuntimeException ex)
{
requestStop = true;
errorMessage = "Error setting camera flash status. Your device may be unsupported.";
}
}
cam.release();
isRunning = false;
requestStop=false;
controller.mHandler.post(controller.mShowToastRunnable);
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/TableLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<SeekBar
android:id="#+id/SeekBar01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="100"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:progress="0"
android:layout_alignParentTop="true"
>
</SeekBar>
<ImageButton
android:id="#+id/btnSwitch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/w_led_on"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"/>
</RelativeLayout>

Need help debugging: Failure delivering result - java.lang.NullPointerException

I have looked around through the other questions with the same problem, but because this error is specific to everyone's personal code, they didn't help much. I'm getting the following error:
(I can't upload images yet, and Eclipse won't let me copy+paste the error, so because I'm lazy, here's a Gyazo: CLICK ME)
Here's my code:
Mikey.java (ignore the stupid names)
package com.jamco.apps.mikey;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Random;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
public class Mikey extends Activity implements RecognitionListener, OnClickListener, TextToSpeech.OnInitListener {
protected static final int REQUEST_OK = 1;
private ImageButton btn;
private TextToSpeech tts;
private TextView txt;
private String thoughts;
private ArrayList<String> thingsYouSaid;
private Integer numberOfThingsSaid = 0;
#Override
public void onDestroy() {
//Don't forget to shutdown tts!
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mikey);
btn = (ImageButton) findViewById(R.id.imageButton1);
txt = (TextView) findViewById(R.id.textView1);
tts = new TextToSpeech(this, this);
btn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent i = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
try {
startActivityForResult(i, REQUEST_OK);
} catch (Exception e) {
Toast.makeText(this, "Error initializing speech to text engine.", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==REQUEST_OK && resultCode==RESULT_OK) {
numberOfThingsSaid += 1;
ArrayList<String> youJustSaid = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
((TextView)findViewById(R.id.textView1)).setText("You said: " + youJustSaid);
thingsYouSaid.add(youJustSaid.get(0).toString());
think();
}
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.UK);
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
} else {
btn.setEnabled(true);
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
#Override
public void onBeginningOfSpeech() {
//TODO Auto-generated method stub
}
#Override
public void onBufferReceived(byte[] buffer) {
//TODO Auto-generated method stub
}
#Override
public void onEndOfSpeech() {
//TODO Auto-generated method stub
}
#Override
public void onError(int error) {
//TODO Auto-generated method stub
}
#Override
public void onEvent(int eventType, Bundle params) {
//TODO Auto-generated method stub
}
#Override
public void onPartialResults(Bundle partialResults) {
//TODO Auto-generated method stub
}
#Override
public void onReadyForSpeech(Bundle params) {
//TODO Auto-generated method stub
}
#Override
public void onResults(Bundle results) {
//TODO Auto-generated method stub
}
#Override
public void onRmsChanged(float rmsdB) {
//TODO Auto-generated method stub
}
private void speak(String speech) {
tts.speak(speech, TextToSpeech.QUEUE_FLUSH, null);
Toast.makeText(this, speech, Toast.LENGTH_LONG).show();
}
private void think() {
if (thingsYouSaid.get(numberOfThingsSaid) == "Hello" || thingsYouSaid.get(numberOfThingsSaid) == "Hi") {
switch (randInt(0, 2)) {
case 0:
speak("Hello");
case 1:
speak("Hello");
case 2:
speak(thingsYouSaid.get(numberOfThingsSaid));
}
}
}
public static int randInt(int min, int max) {
//Usually this can be a field rather than a method variable
Random rand = new Random();
//nextInt is normally exclusive of the top value,
//so add 1 to make it inclusive
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
}
(Sorry if the formatting is bad, I'm new to this site).
Here is my activity xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".Mikey" >
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="42dp"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="119dp"
android:text="Click the Microphone and ask a question!" />
</RelativeLayout>
The Stack-trace tells me to go to this line:
thingsYouSaid.add(youJustSaid.get(0).toString());
However, after lots of trial and error I can't work out what's wrong with it. I tried adding .toString() just to see if it magically fixed something, but no.
Hopefully someone will be able to help me solve this :)
Merry Christmas!
I don't see anywhere that you are initializing thingsYouSaid;. You declare it like this
private ArrayList<String> thingsYouSaid;
but you don't initialize it. Try changing that to
private ArrayList<String> thingsYouSaid = new ArrayList<String>();
Edit
I haven't worked with TextToSpeech but I can tell you that you are comparing Strings incorrectly here
thingsYouSaid.get(numberOfThingsSaid) == "Hello" || thingsYouSaid.get(numberOfThingsSaid) == "Hi")
inside think(). You should use equals() to compare Strings.
if ((("Hello".equals(thingsYouSaid.get(numberOfThingsSaid))
|| ("Hi".equals(thingsYouSaid.get(numberOfThingsSaid))))
also, you should add break; statements at the end of each case or the logic will fall through even if it matches one of the first case statements.
thingsYouSaid is not instantiated anywhere in your code. You should instantiate it (you can do that while declaring):
ArrayList<String> thingsYouSaid = new ArrayList<String>();

Categories