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>
Related
This is my code I have got repeat one working but I want to be able to repeat all songs so it does not stop playing the music, I also want to be able to repeat one single song. I have tried to find documentation to help me but I haven't found anything. Any help would be appreciated
import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import static android.R.drawable.ic_media_play;
public class MainActivity extends Activity {
private static final int UPDATE_FREQUENCY = 500;
private static final int STEP_VALUE = 5000;
private static final int CALL = 872;
static MediaPlayer mp = null;
private final Handler handler = new Handler();
private TextView selectedFile;
private TextView selectedArtist;
private RecyclerView recyclerView;
private SeekBar seekbar;
private MediaPlayer player;
private ImageButton playButton;
private ImageButton prevButton;
private ImageButton nextButton;
private ImageButton repeatButton;
private ImageButton shuffleButton;
private boolean isStarted = true;
private int currentPosition;
private boolean isMovingSeekBar = false;
private MyRecyclerViewAdapter adapter;
private final Runnable updatePositionRunnable = new Runnable() {
public void run() {
updatePosition();
}
};
private List<Music> musicList;
private boolean isShuffle = false;
private boolean isRepeat = false;
private View.OnClickListener onButtonClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.play:
if (player.isPlaying()) {
handler.removeCallbacks(updatePositionRunnable);
player.pause();
playButton.setImageResource(android.R.drawable.ic_media_play);
} else {
if (isStarted) {
player.start();
playButton.setImageResource(android.R.drawable.ic_media_pause);
updatePosition();
} else {
startPlay(currentPosition);
}
}
break;
case R.id.prev:
startPlay(currentPosition - 1);
break;
case R.id.next:
startPlay(currentPosition + 1);
break;
case R.id.shuffle:
if (isShuffle) {
Collections.shuffle(musicList);
adapter.notifyDataSetChanged();
shuffleButton.setColorFilter(-16776961);
} else {
sortMusicList();
shuffleButton.setColorFilter(-16777216);
}
isShuffle = !isShuffle;
break;
case R.id.repeat: {
if (isRepeat) {
player.setLooping(true);
repeatButton.setImageResource(R.drawable.ic_repeat_black_24dp);
repeatButton.setColorFilter(-16776961);
} else {
player.setLooping(false);
repeatButton.setColorFilter(-16777216);
}
break;
}
}
}
};
private void sortMusicList() {
Collections.sort(musicList, new Comparator<Music>() {
#Override
public int compare(Music o1, Music o2) {
return o1.getArtists().compareTo(o2.getArtists());
}
});
if (adapter != null) {
adapter.notifyDataSetChanged();
}
}
private MediaPlayer.OnCompletionListener onCompletion = new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
stopPlay();
startPlay(currentPosition + 1);
}
};
private MediaPlayer.OnErrorListener onError = new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
return false;
}
};
private SeekBar.OnSeekBarChangeListener seekBarChanged = new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
isMovingSeekBar = false;
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
isMovingSeekBar = true;
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (isMovingSeekBar) {
player.seekTo(progress);
Log.i("OnSeekBarChangeListener", "onProgressChanged");
} else {
TextView duration = findViewById(R.id.song_duration);
duration.setText(String.valueOf(progress));
long totalSeconds = TimeUnit.MILLISECONDS.toSeconds(progress);
long minss = totalSeconds / 60;
long seconds = totalSeconds % 60;
duration.setText(String.format(Locale.UK, "%02d:%02d", minss, seconds));
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
recyclerView = findViewById(R.id.list);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
int permissionCheck = ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE);
if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
setupUI();
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
CALL);
}
}
#Override
protected void onPause() {
super.onPause();
player.getCurrentPosition();
}
private void setupUI() {
selectedFile = findViewById(R.id.selected_file);
selectedArtist = findViewById(R.id.artists);
seekbar = findViewById(R.id.seekbar);
prevButton = findViewById(R.id.prev);
playButton = findViewById(R.id.play);
nextButton = findViewById(R.id.next);
repeatButton = findViewById(R.id.repeat);
shuffleButton = findViewById(R.id.shuffle);
player = new MediaPlayer();
player.setOnCompletionListener(onCompletion);
player.setOnErrorListener(onError);
seekbar.setOnSeekBarChangeListener(seekBarChanged);
musicList = new MusicManager().getMusic(getContentResolver());
sortMusicList();
adapter = new MyRecyclerViewAdapter(musicList);
adapter.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
startPlay(position);
}
});
recyclerView.setAdapter(adapter);
prevButton.setOnClickListener(onButtonClick);
playButton.setOnClickListener(onButtonClick);
nextButton.setOnClickListener(onButtonClick);
shuffleButton.setOnClickListener(onButtonClick);
repeatButton.setOnClickListener(onButtonClick);
}
#Override
protected void onDestroy() {
super.onDestroy();
handler.removeCallbacks(updatePositionRunnable);
player.stop();
player.reset();
player.release();
player = null;
}
private void startPlay(int position) {
if (position < 0) {
position = 0;
}
if (position >= musicList.size()) {
position = musicList.size() - 1;
}
String file = musicList.get(position).getFile();
String title = musicList.get(position).getTitle();
String artists = musicList.get(position).getArtists();
currentPosition = position;
if (artists != null) {
selectedArtist.setText(artists);
}
if (title != null) {
selectedFile.setText(title);
}
seekbar.setProgress(0);
updatePosition();
player.stop();
player.reset();
try {
player.setDataSource(file);
player.prepare();
player.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
seekbar.setMax(player.getDuration());
playButton.setImageResource(android.R.drawable.ic_media_pause);
isStarted = true;
}
private void stopPlay() {
player.stop();
player.reset();
playButton.setImageResource(ic_media_play);
handler.removeCallbacks(updatePositionRunnable);
isStarted = false;
}
private void updatePosition() {
handler.removeCallbacks(updatePositionRunnable);
seekbar.setProgress(player.getCurrentPosition());
handler.postDelayed(updatePositionRunnable, UPDATE_FREQUENCY);
if (adapter == null) {
return;
}
}
}
this is just the main activity if you need anything else just ask.
To play a list of songs loop continuously, you can define a variable to be used as an index of the number of songs completed. After completion of the of the list, replay the list of songs by calling the index again. An example of this is:
int[] myAudio = {R.raw.audio1, R.raw.audio2, R.raw.audio3};
int mSongFinish = 0;
MediaPlayer mp = MediaPlayer.create(this, myAudio[0]);
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mSongFinish++;
mp.reset();
if (mSongFinish < myAudio.length()) {
try {
AssetFileDescriptor asset = getResources().openRawResourceFd(myAudio[mSongFinish]);
if (asset != null) {
mp.setDataSource(afd.getFileDescriptor(), asset.getStartOffset(), asset.getLength());
asset.close();
mp.prepare();
}
} catch (Exception ex) {
// report a crash
}
} else {
mSongFinish=0;
mp.release();
mp = null; // either set counter to 0 and start again or call end of list
}
}
});
mp.start();
To do this on a button click, just use an onClickListener. To loop a single song on button click, use mp.setLooping(true).
I Want To Add A Switch Camera Button To My Code.
Here is The Code.
I am not getting how do i do it.
Please Suggest Some Methods.
Thank you in Advance.
CameraDemo.java
public class CameraDemo extends Activity {
private static final String TAG = "CameraDemo";
Camera camera;
Preview preview;
Button buttonClick,switchCam;
int which=0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
switchCam=(Button)findViewById(R.id.switchcam);
preview = new Preview(this);
((RelativeLayout) findViewById(R.id.preview)).addView(preview);
buttonClick = (Button) findViewById(R.id.buttonClick);
buttonClick.setOnClickListener( new OnClickListener() {
public void onClick(View v) {
preview.camera.takePicture(shutterCallback, rawCallback, jpegCallback);
AlertDialog.Builder alertDialog = new AlertDialog.Builder(CameraDemo.this);
// Setting Dialog Title
alertDialog.setTitle("Confirm");
// Setting Dialog Message
alertDialog.setMessage("Are You Done ?");
// Setting Icon to Dialog
alertDialog.setIcon(R.drawable.doneimg);
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(CameraDemo.this);
// Setting Dialog Title
alertDialog.setTitle("Confirm Student");
// Setting Dialog Message
alertDialog.setMessage("Are you a Student?");
// Setting Icon to Dialog
alertDialog.setIcon(R.drawable.student);
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
// Write your code here to invoke YES event
Intent i = new Intent(getApplicationContext(),
ScanId.class);
startActivity(i);
finish();
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to invoke NO event
Toast.makeText(getApplicationContext(), "Sorry, Only Students Allowed", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to invoke NO event
Toast.makeText(getApplicationContext(), "Sorry, Only Students Allowed", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
});
Log.d(TAG, "onCreate'd");
}
ShutterCallback shutterCallback = new ShutterCallback() {
public void onShutter() {
Log.d(TAG, "onShutter'd");
}
};
/** Handles data for raw picture */
PictureCallback rawCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
Log.d(TAG, "onPictureTaken - raw");
}
};
/** Handles data for jpeg picture */
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
FileOutputStream outStream = null;
long time = 0;
try {
// write to local sandbox file system
// outStream = CameraDemo.this.openFileOutput(String.format("%d.jpg", System.currentTimeMillis()), 0);
// Or write to sdcard
time = System.currentTimeMillis();
outStream = new FileOutputStream(String.format("/sdcard/%d.jpg",time));
outStream.write(data);
outStream.close();
Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
Log.d(TAG, "onPictureTaken - jpeg");
}
};
}
NExxt Java File >> Preview.java
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.hardware.Camera;
import android.hardware.Camera.PreviewCallback;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
class Preview extends SurfaceView implements SurfaceHolder.Callback {
private static final String TAG = "Preview";
SurfaceHolder mHolder;
public Camera camera;
int which=0;
Preview(Context context) {
super(context);
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, acquire the camera and tell it where
// to draw.
camera = Camera.open();
try {
camera.setPreviewDisplay(holder);
camera.setDisplayOrientation(90);
camera.setPreviewCallback(new PreviewCallback() {
public void onPreviewFrame(byte[] data, Camera arg1) {
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(String.format("/sdcard/%d.jpg", System.currentTimeMillis()));
outStream.write(data);
outStream.close();
Log.d(TAG, "onPreviewFrame - wrote bytes: " + data.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
Preview.this.invalidate();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// Surface will be destroyed when we return, so stop the preview.
// Because the CameraDevice object is not a shared resource, it's very
// important to release it when the activity is paused.
camera.stopPreview();
camera = null;
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// Now that the size is known, set up the camera parameters and begin
// the preview.
Camera.Parameters parameters = camera.getParameters();
// parameters.setPreviewSize(w, h);
camera.setParameters(parameters);
camera.startPreview();
}
#Override
public void draw(Canvas canvas) {
super.draw(canvas);
Paint p= new Paint(Color.RED);
Log.d(TAG,"draw");
canvas.drawText("PREVIEW", canvas.getWidth()/2, canvas.getHeight()/2, p );
}
}
XML FILE
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:id="#+id/layout">
<RelativeLayout android:id="#+id/preview"
android:layout_weight="1" android:layout_width="fill_parent"
android:layout_height="match_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/switchcam"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="170dp" />
</RelativeLayout>
<Button android:layout_width="80dp"
android:layout_height="80dp"
android:id="#+id/buttonClick"
android:text=""
android:layout_gravity="center_horizontal|bottom"
android:layout_marginBottom="50dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:background="#drawable/circlebutton"
/>
<Button
android:layout_width="40dp"
android:layout_height="40dp"
android:id="#+id/gallery"
android:background="#drawable/grid"
android:layout_marginBottom="50dp"
android:layout_marginLeft="60dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
Just reopen camera with open(int cameraId) method.
//swap the id of the camera to be used
if(currentCameraId == Camera.CameraInfo.CAMERA_FACING_BACK){
currentCameraId = Camera.CameraInfo.CAMERA_FACING_FRONT;
}
else {
currentCameraId = Camera.CameraInfo.CAMERA_FACING_BACK;
}
camera = Camera.open(currentCameraId);
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>();
I'm developing an application. When i exit from the application, it will be opened again (The first activity is called again and again). So i couldn't able to exit from it.
In some other activities I use EXIT button and proper code to exit. Even when I click the EXIT button on those activities, it will start login activity. (login page is opened)
In my application, I use
1) Main
2) ScreenActivity
3) Login
flow: (from main->screenActivity->login)
The start page (1st activity) is posted below
public class main extends Activity {
static ConnectivityManager conMgr;
BackgroundThread backgroundThread;
TextView myText;
boolean myTextOn = true;
Cursor cursor;
String response="";
public SQLiteAdapter mySQLiteAdapter;
private SQLiteDatabase sqLiteDatabase;
SimpleCursorAdapter cursorAdapter;
public class BackgroundThread extends Thread {
boolean running = false;
void setRunning(boolean b){
running = b;
}
#Override
public void run() {
// TODO Auto-generated method stub
//super.run();
while(running){
try {
sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch(Exception e)
{
}
handler.sendMessage(handler.obtainMessage());
}
}
}
Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
//super.handleMessage(msg);
if (myTextOn){
myTextOn = false;
myText.setVisibility(View.GONE);
}
else{
myTextOn = true;
myText.setVisibility(View.VISIBLE);
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.thread);
myText = (TextView)findViewById(R.id.mytext);
}
#Override
protected void onStart() {
conMgr = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
// TODO Auto-generated method stub
super.onStart();
if(isInternetAvailable())
{
Toast.makeText(this, "online", Toast.LENGTH_LONG).show();
startActivity(new Intent(main.this, ScreenActivity.class));
}
else{
startActivity(new Intent(main.this, splashscreen.class));
Toast.makeText(this, "offline", Toast.LENGTH_LONG).show();
}
backgroundThread = new BackgroundThread();
backgroundThread.setRunning(true);
backgroundThread.start();
}
private boolean isInternetAvailable() {
ConnectivityManager cm=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
boolean retry = true;
backgroundThread.setRunning(false);
while(retry){
try {
backgroundThread.join();
retry = false;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch(Exception e)
{
}
}
}
public void onDEstroy()
{
super.onDestroy();
}
}
ScreenActivity:
public class ScreenActivity extends Activity implements AnimationListener {
private TextView animatedView3;
//ImageView image;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
/* Animation animation1 = AnimationUtils.loadAnimation(this,
R.anim.anima);
animation1.setAnimationListener(this);
View animatedView1 = findViewById(R.id.aet1);
animatedView1.startAnimation(animation1);
/** set time to splash out */
final int welcomeScreenDisplay = 9000;
/** create a thread to show splash up to splash time */
Thread welcomeThread = new Thread() {
int wait = 0;
#Override
public void run() {
try {
super.run();
/**
* use while to get the splash time. Use sleep() to increase
* the wait variable for every 100L.
*/
while (wait < welcomeScreenDisplay) {
sleep(100);
wait += 100;
}
} catch (Exception e) {
System.out.println("EXc=" + e);
} finally {
/**
* Called after splash times up. Do some action after splash
* times up. Here we moved to another main activity class
*/
startActivity(new Intent(ScreenActivity.this,
login.class));
}
}
};
welcomeThread.start();
}
public void onAnimationStart(Animation animation) {
}
public void onAnimationEnd(Animation animation) {
//Toast.makeText(this, "Animation ended", Toast.LENGTH_SHORT).show();
if (animatedView3.getVisibility() == View.VISIBLE) {
animatedView3.setVisibility(View.INVISIBLE);
} else {
animatedView3.setVisibility(View.VISIBLE);
}
}
public void onAnimationRepeat(Animation animation) {
// Toast.makeText(this, "Animation rep", Toast.LENGTH_SHORT).show();
}
}
Please can anyone explain about the problem and how to solve it? I didn't understand.
Place finish() in your loginActivity and for other Activities as well else stack will store the list of visited Activities.
I would like to write a real time counter. I tried to use thread, but android warned me that only activity thread may touch the view. I found a solution with runOnUiThread, but it does not work too
public class CounterInRealTimeExampleActivity extends Activity {
private TextView textView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout layout = new LinearLayout(this);
textView = new TextView(this);
textView.setTag(new Integer(0));
layout.addView(textView);
setContentView(layout);
runOnUiThread(new Runnable() {
#Override
public void run() {
//while(true)
{
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
increment();
}
}
});
}
public void increment() {
textView.setTag(new Integer((Integer)textView.getTag())+1);
textView.setText(Integer.toString((Integer)textView.getTag()));
}
}
i am pasting code here. may this help you..
class UpdateTimeTask extends TimerTask {
public void run() {
String time = DateUtils.now("hh:mm:ss'T'a");
String[]arrValues = time.split("T");
if(arrValues.length>0) {
String strValue= arrValues[0];
String []arrTimeValues = strValue.split(":");
String strValue1= arrTimeValues[2];
setTimertext(strValue1);
}
}
public void setTimertext(String strValue) {
runOnUiThread(new Runnable() {
public void run() {
FinalTime=timer_time--;
btnTimer.setText(String.valueOf(FinalTime));
}
});
}
}
Thread.sleep(3000);
is definitely a problem. You aren't allowed to block the UI-thread, which is exactly what sleep does. You have to execute the code to update the UI from within runOnUiThread solely.
working one, found solution after Hasmukh tip
package com.android.examples;
import java.util.Calendar;
import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;
public class CounterInRealTimeExampleActivity extends Activity {
private TextView textView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout layout = new LinearLayout(this);
textView = new TextView(this);
layout.addView(textView);
setContentView(layout);
new Thread(new Runnable() {
#Override
public void run() {
while (true) {
updateTime();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
}
private void updateTime() {
runOnUiThread(new Runnable() {
#Override
public void run() {
textView.setText(Integer.toString((int) (Calendar.getInstance()
.getTimeInMillis() / 1000) % 60));
}
});
}
}