Embedding a Voice in application, Android - android

This is my code's body, I want to embed the voice using TextToSpeech to read "Color is RED" and I don't know where and how to put it
It always having problem by defining the variable for the String and TextToSpeech.
Any help?
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonLoadImage = (Button)findViewById(R.id.loadimage);
targetImage = (ImageView)findViewById(R.id.targetimage);
buttonLoadImage.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 0);
}});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK){
Uri targetUri = data.getData();
Bitmap bitmap;
try {
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(targetUri));
targetImage.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
final TextView textView = (TextView)findViewById(R.id.textView);
final TextView textViewCol = (TextView)findViewById(R.id.textViewColor);
final TextView textViewVal = (TextView)findViewById(R.id.textViewValue);
targetImage.setOnTouchListener(new ImageView.OnTouchListener(){
TextToSpeech mTts ;
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
textView.setText("Touch coordinates : " +
String.valueOf(event.getX()) + "x" + String.valueOf(event.getY()));
ImageView imageView = ((ImageView)v);
Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
int pixel = bitmap.getPixel((int)event.getX(),(int)event.getY());
textViewVal.setText("[" + Color.red(pixel) + "," + Color.green(pixel) + "," + Color.blue(pixel) + "]");
if ((Color.red(pixel) > 200) && (Color.blue(pixel) < 10) && (Color.green(pixel) < 10)) {
textViewCol.setText("Color is Red.");
}
return true; }
});
}
protected int valueOf(float x) {
// TODO Auto-generated method stub
return 0;
}
}

You should read the article here: http://developer.android.com/resources/articles/tts.html
But to do some simple text to speech, use code a bit like this:
private TextToSpeech mTts;
private ImageView targetImage;
private TextView textView;
private TextView textViewCol;
private TextView textViewVal;
private boolean hasTTSBeenInitialized = false;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonLoadImage = (Button) findViewById(R.id.loadimage);
textView = (TextView) findViewById(R.id.textView);
textViewCol = (TextView) findViewById(R.id.textViewColor);
targetImage = (ImageView) findViewById(R.id.targetimage);
textViewVal = (TextView) findViewById(R.id.textViewValue);
buttonLoadImage.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 0);
}
});
//Initialise tts here so you can use it at anytime in the activity.
mTts = new TextToSpeech(this, new OnInitListener() {
#Override
public void onInit(int status) {
hasTTSBeenInitialized = true;
}
});
mTts.setLanguage(Locale.US);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
Uri targetUri = data.getData();
Bitmap bitmap;
try {
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(targetUri));
targetImage.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
targetImage.setOnTouchListener(touchListener);
}
OnTouchListener touchListener = new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
textView.setText("Touch coordinates : " + String.valueOf(event.getX()) + "x" + String.valueOf(event.getY()));
ImageView imageView = ((ImageView) v);
Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
int pixel = bitmap.getPixel((int) event.getX(), (int) event.getY());
textViewVal.setText("[" + Color.red(pixel) + "," + Color.green(pixel) + "," + Color.blue(pixel) + "]");
if ((Color.red(pixel) > 200) && (Color.blue(pixel) < 10) && (Color.green(pixel) < 10)) {
//only attempt to play if tts has been initialised, if it hasnt then play it later when it has been initialised
if(hasTTSBeenInitialized){
mTts.speak("Color is Red", TextToSpeech.QUEUE_FLUSH, null);
}else{
//Maybe add it to a queue to play when it has been initialized
}
textViewCol.setText("Color is Red.");
}
return true;
}
};

Related

I can't load image from gallery and set it into ImageView

I try set image into ImageView from gallery.
public class CollageCreateActivity extends AppCompatActivity {
private static final String TAG ="MyLogs" ;
Draw2d draw2d;
static final int GALLERY_REQUEST = 1;
private final int TAKE_PICTURE_CAMERA = 2;
private Uri mOutputFileUri;
ArrayList<CollageView> collageViewList1;
ArrayList<CollageView> collageViewList2;
float width;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.collage_creator);
collageViewList1 = new ArrayList<>();
collageViewList2 = new ArrayList<>();
Data data = new Data();
draw2d = new Draw2d(this);
LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
FrameLayout frameLayout = (FrameLayout) findViewById(R.id.frame_1);
if (frameLayout != null) {
frameLayout.addView(draw2d);
}
createCollage(data, layout);
if (layout != null) {
layout.bringToFront();
}
click();
}
public void createCollage(Data data, LinearLayout layout) {
ArrayList<Integer> list = new ArrayList<>();
list.add((int) data.getMap().get("mainLayout"));
list.add((int) data.getMap().get("firstLayout"));
list.add((int) data.getMap().get("secondLayout"));
final LinearLayout layout1 = new LinearLayout(this);
final LinearLayout layout2 = new LinearLayout(this);
LinearLayout[] massLay = {layout, layout1, layout2};
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
params.weight = 1;
layout1.setLayoutParams(params);
layout2.setLayoutParams(params);
for (int i = 0; i < (int) data.getMap().get("layButt1"); i++) {
final Button button = new Button(this);
button.setLayoutParams(params);
button.setTextSize(50);
button.setId(i);
button.setPadding(16, 16, 16, 16);
button.setText(R.string.plus);
layout1.addView(button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
layout1.removeView(v);
CollageView collageView = new CollageView(CollageCreateActivity.this);
saveFromGallery();
layout1.addView(collageView);
collageView.setOnTouchListener(new MultiTouchListener());
collageViewList1.add(collageView);
}
});
}
for (int j = 0; j < (int) data.getMap().get("layButt2"); j++) {
Button button2 = new Button(this);
button2.setLayoutParams(params);
button2.setTextSize(50);
button2.setId(j);
button2.setPadding(16, 16, 16, 16);
button2.setText(R.string.plus);
layout2.addView(button2);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
layout2.removeView(v);
CollageView collageView = new CollageView(CollageCreateActivity.this);
layout2.addView(collageView);
collageView.setOnTouchListener(new MultiTouchListener());
width = layout2.getWidth();
collageViewList2.add(collageView);
}
});
}
for (int x = 0; x < list.size(); x++) {
if (list.get(x) == 0) {
massLay[x].setOrientation(LinearLayout.HORIZONTAL);
} else {
massLay[x].setOrientation(LinearLayout.VERTICAL);
}
}
layout.addView(layout1);
layout.addView(layout2);
}
public void click() {
Button button = (Button) findViewById(R.id.butt);
if (button != null) {
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < collageViewList1.size(); i++) {
collageViewList1.get(i).setDrawingCacheEnabled(true);
Bitmap bitmap1 = Bitmap.createBitmap(collageViewList1.get(i).getDrawingCache());
collageViewList1.get(i).setDrawingCacheEnabled(false);
draw2d.listBitmap.add(bitmap1);
draw2d.listX.add(collageViewList1.get(i).getX());
draw2d.listY.add(collageViewList1.get(i).getY());
Log.d("TAG", collageViewList1.get(i).getX() + " " + collageViewList1.get(i).getY());
}
for (int i = 0; i < collageViewList2.size(); i++) {
collageViewList2.get(i).setDrawingCacheEnabled(true);
Bitmap bitmap2 = Bitmap.createBitmap(collageViewList2.get(i).getDrawingCache());
collageViewList2.get(i).setDrawingCacheEnabled(false);
draw2d.listBitmap.add(bitmap2);
draw2d.listX.add(collageViewList2.get(i).getX() + width);
draw2d.listY.add(collageViewList2.get(i).getY());
Log.d("TAG", collageViewList1.get(i).getX() + " " + collageViewList1.get(i).getY());
}
draw2d.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(draw2d.getDrawingCache());
draw2d.setDrawingCacheEnabled(false);
draw2d.invalidate();
}
});
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap bitmap = null;
InputStream imageStream = null;
CollageView collageView = new CollageView(CollageCreateActivity.this);
switch(requestCode) {
case GALLERY_REQUEST:
if(resultCode == RESULT_OK){
Uri selectedImage = data.getData();
try {
imageStream=getContentResolver().openInputStream(selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
bitmap= BitmapFactory.decodeStream(imageStream);
Log.d(TAG, "сетим з галереї1");
collageView.setImageBitmap(bitmap);
Log.d(TAG, "сетим з галереї");
}
break;
case TAKE_PICTURE_CAMERA:
if (data != null) {
if (data.hasExtra("data")) {
Bitmap thumbnailBitmap = data.getParcelableExtra("data");
collageView.setImageBitmap(thumbnailBitmap);
}
} else {
collageView.setImageURI(mOutputFileUri);
}
}
}
private void saveFromGallery(){
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, GALLERY_REQUEST);
}
}
When i try set image from folder "drawrable" it's work, but if i try load image and set from gallery it's don't work, all i have "W/EGL_genymotion: eglSurfaceAttrib not implemented" in logs
In this case you will have to create a content provider which will use to share your local (Application's internal) file to the camera activity.when you try to take picture from camera
try this code:
Content provider class
public class MyFileContentProvider extends ContentProvider {
public static final Uri CONTENT_URI =
Uri.parse("content://com.example.camerademo/");
private static final HashMap<String, String> MIME_TYPES = new
HashMap<String, String>();
static {
MIME_TYPES.put(".jpg", "image/jpeg");
MIME_TYPES.put(".jpeg", "image/jpeg");
}
#Override
public boolean onCreate() {
try {
File mFile = new File(getContext().getFilesDir(), "newImage.jpg");
if(!mFile.exists()) {
mFile.createNewFile();
}
getContext().getContentResolver().notifyChange(CONTENT_URI, null);
return (true);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
#Override
public String getType(Uri uri) {
String path = uri.toString();
for (String extension : MIME_TYPES.keySet()) {
if (path.endsWith(extension)) {
return (MIME_TYPES.get(extension));
}
}
return (null);
}
#Override
public ParcelFileDescriptor openFile(Uri uri, String mode)
throws FileNotFoundException {
File f = new File(getContext().getFilesDir(), "newImage.jpg");
if (f.exists()) {
return (ParcelFileDescriptor.open(f,
ParcelFileDescriptor.MODE_READ_WRITE));
}
throw new FileNotFoundException(uri.getPath());
}
#Override
public Cursor query(Uri url, String[] projection, String selection,
String[] selectionArgs, String sort) {
throw new RuntimeException("Operation not supported");
}
#Override
public Uri insert(Uri uri, ContentValues initialValues) {
throw new RuntimeException("Operation not supported");
}
#Override
public int update(Uri uri, ContentValues values, String where,
String[] whereArgs) {
throw new RuntimeException("Operation not supported");
}
#Override
public int delete(Uri uri, String where, String[] whereArgs) {
throw new RuntimeException("Operation not supported");
}
}
Home.java:
public class Home extends Activity implements OnClickListener{
/** Called when the activity is first created. */
private final int CAMERA_RESULT = 1;
private final String Tag = getClass().getName();
Button button1;
ImageView imageView1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button1 = (Button)findViewById(R.id.button1);
imageView1 = (ImageView)findViewById(R.id.imageView1);
button1.setOnClickListener(this);
}
public void onClick(View v) {
PackageManager pm = getPackageManager();
if (pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, MyFileContentProvider.CONTENT_URI);
startActivityForResult(i, CAMERA_RESULT);
} else {
Toast.makeText(getBaseContext(), "Camera is not available",
Toast.LENGTH_LONG).show();
} }
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
super.onActivityResult(requestCode, resultCode, data);
Log.i(Tag, "Receive the camera result");
if (resultCode == RESULT_OK && requestCode == CAMERA_RESULT) {
File out = new File(getFilesDir(), "newImage.jpg");
if(!out.exists()) {
Toast.makeText(getBaseContext(),
"Error while capturing image", Toast.LENGTH_LONG)
.show();
return;
}
Bitmap mBitmap = BitmapFactory.decodeFile(out.getAbsolutePath());
imageView1.setImageBitmap(mBitmap);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
imageView1 = null;
}
}
hope it will help you,otherwise u will contact me my email
id:daminimehra28#gmail.com

How to use different button to access same class?

I have three activity.
A>>B>>C
C>>return image and value to B>>return to A>>If textView not null can intent to B
C has a camera function which will return the image from B to A.
In A, it has one editText and a button. If editText not null, it can be clicked and intent to B by passing the value and image for edit. But the problem now is, when I click the button, I will see the image display on the image view even it is not get the image from c!
I know I can use view.setImageDrawable(null) to clear the image but it cannot work in my case since I access the B two times with different widget!
Activity C
ok.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0) //return to B
{
Intent returnIntent=new Intent();
text=t.getText().toString();
b.setDrawingCacheEnabled(true);
b.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
b.layout(0, 0, b.getMeasuredWidth(), b.getMeasuredHeight());
b.buildDrawingCache(true);
returnIntent.putExtra("text", text);
if (b.getDrawingCache() != null) {
Bitmap bitmap = Bitmap.createBitmap(b.getDrawingCache());
if (bitmap == null) {
Log.e("TAG", "getDrawingCache() == null");
}
Global.img = bitmap;
}
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
}
Activity B
public void onActivityResult(int requestCode,int resultCode, Intent data)
{ //receive value and image from C
if(requestCode==PROJECT_REQUEST_CODE) {
if(data!=null&&data.hasExtra("text")) {
c = data.getStringExtra("text");
txt1.setText(c);
viewImage.setImageBitmap(Global.img);
}
}
else if (requestCode==CAMERA_REQUEST_CODE)
{
}
}
b.setOnClickListener(new View.OnClickListener() { // back to A
public void onClick(View arg0) {
Intent returnIntent = new Intent();
a = "Project";
text = txt.getText().toString(); // amount
returnIntent.putExtra("text", text);
returnIntent.putExtra("a", a);
final int k1 = getIntent().getExtras().getInt("k");
returnIntent.putExtra("k1", k1);
returnIntent.putExtra("c",c);
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
Activity A
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) { //receive data from B
int button = data.getIntExtra("k1", 0);
if (button == 1) {
switch (requestCode) {
case 0:
result = data.getStringExtra("text");
name = data.getStringExtra("a");
description=data.getStringExtra("c");
if (Global.img != null) {
v.setImageBitmap(Global.img);
}
as=Long.parseLong(result);
c.setText(" " + name + "------" + "RM " + result);
break;
}
c.setOnClickListener(new View.OnClickListener() { // if c is not null, it can intent to B.Otherwise it is not clickable
#Override
public void onClick(View view) {
if ((name != null && name.trim().length() > 0) && (result != null && result.trim().length() > 0)) {
Toast.makeText(getActivity().getApplicationContext(), "not null", Toast.LENGTH_LONG).show();
if (name.equals("Project")) {
Intent intent = new Intent(getActivity(), Project1.class);
Global.img = null;
v.setDrawingCacheEnabled(true);
v.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
v.getMeasuredWidth(), v.getMeasuredHeight());
v.buildDrawingCache(true);
intent.putExtra("name", name);
intent.putExtra("result", result);
intent.putExtra("description", description);
if (v.getDrawingCache() != null) {
Bitmap bitmap = Bitmap.createBitmap(v.getDrawingCache());
if (bitmap == null) {
Log.e("TAG", "getDrawingCache() == null");
}
Global.img = bitmap;
startActivity(intent);
}
}
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Toast.makeText(getActivity().getApplicationContext(), fk + "", Toast.LENGTH_LONG).show();
AlertDialogRadio(a1);
}
});
public void AlertDialogRadio(final int k) {
final CharSequence[] ClaimsModel = {"B", "Petrol", "Car Maintenance"};
AlertDialog.Builder alt_bld = new AlertDialog.Builder(getActivity());
alt_bld.setTitle("Select a Claims");
alt_bld.setSingleChoiceItems(ClaimsModel, -1, new DialogInterface
.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
Intent intent = new Intent(getActivity().getApplicationContext(), B.class);
intent.putExtra("k",k);
startActivityForResult(intent, 0);
}else{...}
}
In A I have textView and button. If textView is clicked, it should display an image on B imageView. If button is clicked, nothing should display on B imageView. Please help,I have no idea...
So just simply add intent.putExtra("bitmap",true); in the c.setOnClickListener, then add
viewImage = (ImageView) findViewById(R.id.imageView2);
if(getIntent().getBooleanExtra("bitmap",false))
{
viewImage.setImageBitmap(Global.img);
}
else
{
viewImage.setImageBitmap(null);
}
in onCreate Activity B

How to store video in sd card while sending live streaming on wowza server

I am trying to store video in sd card while sending live streaming on wowza sever. I am sending successfully live video to wowza server but I am not able to store corresponding video to sd card.I am using this library to send video to wowza sever.
surfaceView=(SurfaceView) findViewById(R.id.surface);
myChronometer = (Chronometer) findViewById(R.id.chronometer1);
chat32=(Button) findViewById(R.id.chat32);
chatedit=(EditText) findViewById(R.id.chatedit);
send=(Button) findViewById(R.id.send);
chatlist=(ListView) findViewById(R.id.camerachatlist);
chat32.setOnClickListener(this);
mButtonVideo = (Button) findViewById(R.id.video);
mButtonSave = (Button) findViewById(R.id.save);
mButtonStart = (Button) findViewById(R.id.start);
mButtonFlash = (Button) findViewById(R.id.flash);
mButtonCamera =(Button) findViewById(R.id.camera);
mButtonSettings = (Button) findViewById(R.id.settings);
mSurfaceView = (SurfaceView) findViewById(R.id.surface);
mEditTextURI = (EditText) findViewById(R.id.uri);
mEditTextUsername = (EditText) findViewById(R.id.username);
mEditTextPassword = (EditText) findViewById(R.id.password);
mTextBitrate = (TextView) findViewById(R.id.bitrate);
mLayoutVideoSettings = (FrameLayout) findViewById(R.id.video_layout);
mLayoutServerSettings = (FrameLayout) findViewById(R.id.server_layout);
mRadioGroup = (RadioGroup) findViewById(R.id.radio);
mProgressBar = (ProgressBar) findViewById(R.id.progress_bar);
mRadioGroup.setOnCheckedChangeListener(this);
mRadioGroup.setOnClickListener(this);
mButtonStart.setOnClickListener(this);
mButtonSave.setOnClickListener(this);
mButtonFlash.setOnClickListener(this);
mButtonCamera.setOnClickListener(this);
mButtonVideo.setOnClickListener(this);
mButtonSettings.setOnClickListener(this);
mButtonFlash.setTag("off");
SharedPreferences mPrefs = PreferenceManager
.getDefaultSharedPreferences(VideoStream.this);
if (mPrefs.getString("uri", null) != null)
mLayoutServerSettings.setVisibility(View.GONE);
mEditTextURI.setText(mPrefs.getString("uri",
getString(R.string.default_stream)));
System.out.println("text get from edittext" + mEditTextURI.getText());
mEditTextPassword.setText(mPrefs.getString("password", "********"));
System.out.println("text get from edittext"
+ mEditTextPassword.getText());
mEditTextUsername.setText(mPrefs.getString("username", "*******"));
System.out.println("text get from edittext"
+ mEditTextUsername.getText());
// Configures the SessionBuilder
SessionBuilder sessionbuilder = SessionBuilder.getInstance();
mSession = SessionBuilder.getInstance().setCallback(VideoStream.this)
.setContext(getApplicationContext())
.setAudioEncoder(SessionBuilder.AUDIO_AAC)
.setAudioQuality(new AudioQuality(8000, 16000))
.setVideoEncoder(SessionBuilder.VIDEO_H264)
.setSurfaceView(mSurfaceView).setPreviewOrientation(0)
.build();
// Configures the RTSP client
mClient = new RtspClient();
mClient.setSession(mSession);
mClient.setCallback(VideoStream.this);
System.out.println("helllllllloooo");
// Use this to force streaming with the MediaRecorder API
mSession.getVideoTrack().setStreamingMethod(
MediaStream.MODE_MEDIARECORDER_API);
// Use this to stream over TCP, EXPERIMENTAL!
mClient.setTransportMode(RtspClient.TRANSPORT_TCP);
// Use this if you want the aspect ratio of the surface view to
// respect the aspect ratio of the camera preview
mSurfaceView.setAspectRatioMode(SurfaceView.ASPECT_RATIO_PREVIEW);
mSurfaceView.getHolder().addCallback(this);
selectQuality();
}
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
System.out.println("############## onCheckedChanged");
mLayoutVideoSettings.setVisibility(View.GONE);
mLayoutServerSettings.setVisibility(View.VISIBLE);
selectQuality();
}
// =================================================================
// on click
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.start:
mLayoutServerSettings.setVisibility(View.GONE);
toggleStream();
break;
case R.id.flash:
if (mButtonFlash.getTag().equals("on")) {
mButtonFlash.setTag("off");
mButtonFlash
.setBackgroundResource(R.drawable.ic_flash_on_holo_light);
} else {
mButtonFlash
.setBackgroundResource(R.drawable.ic_flash_off_holo_light);
mButtonFlash.setTag("on");
}
mSession.toggleFlash();
break;
case R.id.camera:
mSession.switchCamera();
break;
case R.id.settings:
if (mLayoutVideoSettings.getVisibility() == View.GONE
&& mLayoutServerSettings.getVisibility() == View.GONE) {
mLayoutServerSettings.setVisibility(View.VISIBLE);
} else {
mLayoutServerSettings.setVisibility(View.GONE);
mLayoutVideoSettings.setVisibility(View.GONE);
}
break;
case R.id.video:
mRadioGroup.clearCheck();
mLayoutServerSettings.setVisibility(View.GONE);
mLayoutVideoSettings.setVisibility(View.VISIBLE);
break;
case R.id.save:
mLayoutServerSettings.setVisibility(View.GONE);
break;
case R.id.chat32:
chatedit.setVisibility(View.VISIBLE);
send.setVisibility(View.VISIBLE);
break;
case R.id.send:
chatlist.setVisibility(View.VISIBLE);
}
}
// ===================================================
#Override
public void onDestroy() {
super.onDestroy();
mClient.release();
mSession.release();
mSurfaceView.getHolder().removeCallback(this);
}
private void selectQuality() {
System.out.println("############## selectQuality");
int id = mRadioGroup.getCheckedRadioButtonId();
RadioButton button = (RadioButton) findViewById(id);
if (button == null)
return;
String text = button.getText().toString();
System.out.println("text " + text);
Pattern pattern = Pattern.compile("(\\d+)x(\\d+)\\D+(\\d+)\\D+(\\d+)");
Matcher matcher = pattern.matcher(text);
matcher.find();
int width = Integer.parseInt(matcher.group(1));
int height = Integer.parseInt(matcher.group(2));
int framerate = Integer.parseInt(matcher.group(3));
int bitrate = Integer.parseInt(matcher.group(4)) * 1000;
mSession.setVideoQuality(new VideoQuality(width, height, framerate,
bitrate));
Toast.makeText(this, ((RadioButton) findViewById(id)).getText(),
Toast.LENGTH_SHORT).show();
Log.d(TAG, "Selected resolution: " + width + "x" + height);
}
private void enableUI() {
System.out.println("############## logError");
mButtonStart.setEnabled(true);
mButtonCamera.setEnabled(true);
}
// Connects/disconnects to the RTSP server and starts/stops the stream
public void toggleStream() {
mProgressBar.setVisibility(View.VISIBLE);
if (!mClient.isStreaming()) {
String ip, port, path;
// We save the content user inputs in Shared Preferences
SharedPreferences mPrefs = PreferenceManager
.getDefaultSharedPreferences(VideoStream.this);
Editor editor = mPrefs.edit();
editor.putString("uri", "********");
editor.putString("password", "***********");
editor.putString("username", "********");
editor.commit();
// String ip, port, path;
// We parse the URI written in the Editext
Pattern uri = Pattern.compile("rtsp://(.+):(\\d+)/(.+)");
Matcher m = uri.matcher(AppConfig.STREAM_URL);
m.find();
ip = m.group(1);
port = m.group(2);
path = m.group(3);
System.out.println("ip " + ip);
System.out.println("port " + port);
System.out.println("path " + path);
/*
* // We parse the URI written in the Editext Pattern uri =
* Pattern.compile("rtsp://(.+):?(\\d*)/(.+)"); Matcher m =
* uri.matcher(mEditTextURI.getText()); m.find(); ip = m.group(1);
* port = m.group(2); path = m.group(3);
* System.out.println("path is "+path);
*
* System.out.println("port is "+port);
* System.out.println("ip is "+ip);
*/
mClient.setCredentials(AppConfig.PUBLISHER_USERNAME,
AppConfig.PUBLISHER_PASSWORD);
mClient.setServerAddress(ip, Integer.parseInt(port));
mClient.setStreamPath("/" + path);
mClient.startStream();
fileUri = getOutputMediaFileUri();
// Start camera preview
mSession.startPreview();
} else {
// Stops the stream and disconnects from the RTSP server
mClient.stopStream();
// stop camera preview
mSession.stopPreview();
}
}
private void logError(final String msg) {
System.out.println("############## logError");
final String error = (msg == null) ? "Error unknown" : msg;
// Displays a popup to report the eror to the user
AlertDialog.Builder builder = new AlertDialog.Builder(VideoStream.this);
builder.setMessage(msg).setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
#Override
public void onBitrateUpdate(long bitrate) {
System.out.println("############## onBitrateUpdate");
mTextBitrate.setText("" + bitrate / 1000 + " kbps");
}
#Override
public void onPreviewStarted() {
System.out.println("############## onPreviewStarted");
if (mSession.getCamera() == CameraInfo.CAMERA_FACING_FRONT) {
mButtonFlash.setEnabled(false);
mButtonFlash.setTag("off");
mButtonFlash.setBackgroundResource(R.drawable.ic_flash_on_holo_light);
} else {
mButtonFlash.setEnabled(true);
}
}
#Override
public void onSessionConfigured() {
System.out.println(" ############## onSessionConfigured");
}
#Override
public void onSessionStarted() {
System.out.println("onSessionStarted");
enableUI();
mButtonStart.setBackgroundResource(R.drawable.record_pressed);
myChronometer.setVisibility(View.VISIBLE);
startTimer();
mProgressBar.setVisibility(View.GONE);
chat32.setVisibility(View.VISIBLE);
}
private void startTimer() {
// TODO Auto-generated method stub
myChronometer.setBase(SystemClock.elapsedRealtime() + timeWhenStopped);
myChronometer.start();
}
#Override
public void onSessionStopped() {
System.out.println(" ############## onSessionStopped");
enableUI();
mButtonStart.setBackgroundResource(R.drawable.record_stop);
mButtonStart.setBackgroundResource(R.drawable.record_stop);
stopTimer();
chat32.setVisibility(View.INVISIBLE);
chatedit.setVisibility(View.INVISIBLE);
send.setVisibility(View.INVISIBLE);
mProgressBar.setVisibility(View.GONE);
}
private void stopTimer() {
// TODO Auto-generated method stub
myChronometer.setBase(SystemClock.elapsedRealtime());
myChronometer.stop();
showElapsedTime();
}
private void showElapsedTime() {
// TODO Auto-generated method stub
long elapsedMillis = SystemClock.elapsedRealtime()
- myChronometer.getBase();
Toast.makeText(VideoStream.this,
"Elapsed milliseconds: " + elapsedMillis, Toast.LENGTH_SHORT).show();
}
#Override
public void onSessionError(int reason, int streamType, Exception e) {
System.out.println(" ############## onSessionError");
mProgressBar.setVisibility(View.GONE);
switch (reason) {
case Session.ERROR_CAMERA_ALREADY_IN_USE:
break;
case Session.ERROR_CAMERA_HAS_NO_FLASH:
mButtonFlash.setBackgroundResource(R.drawable.ic_flash_on_holo_light);
mButtonFlash.setTag("off");
break;
case Session.ERROR_INVALID_SURFACE:
break;
case Session.ERROR_STORAGE_NOT_READY:
break;
case Session.ERROR_CONFIGURATION_NOT_SUPPORTED:
VideoQuality quality = mSession.getVideoTrack().getVideoQuality();
logError("The following settings are not supported on this phone: "
+ quality.toString() + " " + "(" + e.getMessage() + ")");
e.printStackTrace();
return;
case Session.ERROR_OTHER:
break;
}
if (e != null) {
logError(e.getMessage());
e.printStackTrace();
}
}
#Override
public void onRtspUpdate(int message, Exception e) {
System.out.println(" ############## onRtspUpdate");
switch (message) {
case RtspClient.ERROR_CONNECTION_FAILED:
case RtspClient.ERROR_WRONG_CREDENTIALS:
mProgressBar.setVisibility(View.GONE);
enableUI();
logError(e.getMessage());
e.printStackTrace();
break;
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
System.out.println(" ############## surfaceChanged");
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
mSession.startPreview();
System.out.println(" ############## surfaceCreated");
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
mClient.stopStream();
System.out.println(" ############## surfaceDestroyed");
}
}
you can try this ,
// Video from gallery
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(
Intent.createChooser(intent, "Select Video"),
SELECT_VIDEO);
// Video from Camera
state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
mVideoFileTemp = new File(Environment
.getExternalStorageDirectory(),
"Nameofthefile");
} else {
mVideoFileTemp = new File(getApplicationContext()
.getFilesDir(), "Nameofthefile");
}
intent = new Intent(
android.provider.MediaStore.ACTION_VIDEO_CAPTURE);
try {
Uri mImageCaptureUri = null;
// String state = Environment.getExternalStorageState();
if (mVideoFileTemp == null) {
System.out.println("no file found");
} else {
System.out.println("file found");}
if (Environment.MEDIA_MOUNTED.equals(state)) {
mImageCaptureUri = Uri.fromFile(mVideoFileTemp);
} else {
mImageCaptureUri = InternalStorageContentProvider.CONTENT_URI;
}
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
mImageCaptureUri);
intent.putExtra("return-data", true);
startActivityForResult(intent, SELECT_CAMERA_VIDEO_REQUEST);
} catch (ActivityNotFoundException e) {
Log.d("Tag", "cannot take video", e);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_VIDEO && resultCode == Activity.RESULT_OK
&& null != data) {
Uri selectedVideo = data.getData();
String[] filePathColumn = { MediaStore.Video.Media.DATA };
Cursor cursor = getApplicationContext().getContentResolver()
.query(selectedVideo, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String videoPath = cursor.getString(columnIndex);
cursor.close();
videoFile = new File(videoPath);
bitmap_postImage = ThumbnailUtils.createVideoThumbnail(
videoPath, Thumbnails.MICRO_KIND);
setImagePreview(bitmap_postImage);
}
if (requestCode == SELECT_CAMERA_VIDEO_REQUEST
&& resultCode == Activity.RESULT_OK) {
videoFile = mVideoFileTemp;
bitmap_postImage = ThumbnailUtils.createVideoThumbnail(
videoFile.getPath(), Thumbnails.MICRO_KIND);
setImagePreview(bitmap_postImage);
}
}
}

Activity State not saved

I want to save my Activity state while I swipe between activities but I cannot. Some things are saved and the others dont. I think it has to do somehow with the gestureListener I'm impementing but I'm not sure.
When I swipe to a different activity and then back to this one - the AsyncTask is still running and the Handler is still updating the GUI, however, the views I have displaying in this activity and the buttons are all in their initial configuration.
what am I doing wrong?
public class Main extends Activity implements OnClickListener,
SimpleGestureListener {
/** Called when the activity is first created. */
static String checkedIN = "";
private int hoursSum;
private int minutesSum;
static int dayIs;
static String madeSoFar = "";
static int hoursCount = 0;
static String formattedSeconds = "";
static String formattedMinutes = "";
public static NumberFormat formatter = new DecimalFormat("#0.00");
static boolean killcheck = false;
static String time = "";
static Handler mHandler;
private boolean clicked = false;
private boolean wasShift = false;
static String startString;
static String finishString;
private SimpleGestureFilter detector;
private Typeface tf, tf2, roboto;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
// **************** Set Fonts **************
roboto = Typeface.createFromAsset(getAssets(), "fonts/robotothin.ttf");
tf = Typeface.createFromAsset(getAssets(), "fonts/Advert.ttf");
tf2 = Typeface.createFromAsset(getAssets(), "fonts/passion.ttf");
// **************** Gesture implementation ************
detector = new SimpleGestureFilter(this, this);
// **************** Date and Time Objects *************
final Date date = new Date();
final Date today = Calendar.getInstance().getTime();
DateFormat DF = new SimpleDateFormat("dd/MM/yyyy");
final String DateInString = DF.format(today);
String myString = DateFormat.getDateInstance().format(date);
final TextView dateDisplay = (TextView) findViewById(R.id.dateDisplay);
dateDisplay.setText(myString);
final DBAdapter DB = new DBAdapter(this);
// ************* Apply custom fonts ***************
TextView Title = (TextView) findViewById(R.id.textView2);
Title.setTypeface(tf);
final TextView Author = (TextView) findViewById(R.id.textView3);
Author.setTypeface(roboto);
TextView Current = (TextView) findViewById(R.id.textView1);
Current.setTypeface(roboto);
DigitalClock DG = (DigitalClock) findViewById(R.id.digitalClock1);
DG.setTypeface(roboto);
TextView dater = (TextView) findViewById(R.id.date);
dater.setTypeface(roboto);
TextView dateDisp = (TextView) findViewById(R.id.dateDisplay);
dateDisp.setTypeface(roboto);
CheckedTextView CV = (CheckedTextView) findViewById(R.id.radioButton1);
CV.setTypeface(roboto);
// *************************************************//
final Button checkIn = (Button) findViewById(R.id.CheckIn);
checkIn.setTypeface(roboto);
CheckedTextView check = (CheckedTextView) findViewById(R.id.radioButton1);
Boolean enable = false;
check.setEnabled(enable);
mHandler = new Handler() {
public void handleMessage(Message msg) {
time = "Time: " + hoursCount + ":" + formattedMinutes + ":"
+ formattedSeconds + " Money: " + madeSoFar;
Author.setText(time);
}
};
// **************** Click Listener for first Check In Button
checkIn.setOnClickListener(new OnClickListener() {
int startHours;
int startMinutes;
int finishHours;
int finishMinutes;
#Override
public void onClick(View v) {
// Check Out
if (clicked == true) {
killcheck = true;
checkedIN = "Check In";
checkIn.setText(checkedIN);
finishHours = Utility.getHoursTime();
finishMinutes = Utility.getMinutesTime();
finishString = Integer.toString(Utility.getHoursTime())
+ ":" + Integer.toString(Utility.getMinutesTime())
+ " -";
clicked = false;
wasShift = true;
hoursSum = finishHours - startHours;
minutesSum = finishMinutes - startMinutes;
// Check In
} else if (clicked == false) {
checkedIN = "Check Out";
checkIn.setText(checkedIN);
killcheck = false;
new ShiftProgress().execute();
startHours = Utility.getHoursTime();
startMinutes = Utility.getMinutesTime();
startString = Integer.toString(Utility.getHoursTime())
+ ":" + Integer.toString(Utility.getMinutesTime())
+ " -";
String s = "In Shift ";
CheckedTextView radio = (CheckedTextView) findViewById(R.id.radioButton1);
radio.setText(s);
clicked = true;
}
}
});
Button addShift = (Button) findViewById(R.id.addShift);
addShift.setTypeface(tf2);
// **************** On click listener for adding a shift
addShift.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (wasShift == true) {
changeDateToString(DateInString);
DB.open();
final Cursor cursor = DB.getAllShifts();
startManagingCursor(cursor);
cursor.moveToLast();
int count = cursor.getPosition();
final int position = count + 2;
cursor.moveToNext();
GregorianCalendar GC = new GregorianCalendar();
DB.addToDBTotal(DateInString, "Money: " + madeSoFar,
hoursSum, minutesSum,
Utility.getDay(GC.get(Calendar.DAY_OF_WEEK)),
position, startString, finishString);
DBAdapter.close();
wasShift = false;
printAny(getApplicationContext(), "Added to Shifts",
Toast.LENGTH_SHORT);
} else {
printAny(getApplicationContext(), "Please Check In First", Toast.LENGTH_SHORT);
}
}
});
}
// **************** METHOD DECLERATIONS ****
public void viewShifts() {
Intent myIntent = new Intent(Main.this, Shifts.class);
startActivity(myIntent);
}
public void changeDateToString(String s) {
Utility.INSTANCE.setDate(s);
}
public void changeDurationToString(String s) {
Utility.INSTANCE.setDuration(s);
}
public void printAny(Context c, CharSequence s, int i) {
Context context = c;
CharSequence text = s;
final int duration = i;
Toast toast = Toast.makeText(context, text, duration);
toast.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER, 0, 0);
toast.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.exit:
System.exit(1);
DBAdapter.close();
return true;
case R.id.view:
viewShifts();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
#Override
public void onSwipe(int direction) {
Intent intent = new Intent();
switch (direction) {
case SimpleGestureFilter.SWIPE_RIGHT:
intent.setClass(this, Shifts.class);
startActivity(intent);
break;
case SimpleGestureFilter.SWIPE_LEFT:
intent.setClass(this, Shifts.class);
startActivity(intent);
break;
}
}
#Override
public boolean dispatchTouchEvent(MotionEvent me) {
this.detector.onTouchEvent(me);
return super.dispatchTouchEvent(me);
}
#Override
public void onDoubleTap() {
// TODO Auto-generated method stub
}
public class ShiftProgress extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
int count = 0;
int seconds = 0;
int minutesTime = 0;
int minutesCount = 1;
for (;;) {
if (seconds % 60 == 0) {
minutesTime = count / 60;
seconds = 0;
}
if (seconds < 10) {
formattedSeconds = String.format("%02d", seconds);
}
else if (seconds >= 10) {
formattedSeconds = String.valueOf(seconds);
}
if (minutesTime < 10) {
formattedMinutes = String.format("%02d", minutesTime);
}
else if (minutesTime >= 10) {
formattedMinutes = String.valueOf(minutesTime);
}
if (minutesTime % 60 == 0) {
hoursCount = minutesCount / 60;
minutesTime = 0;
}
double sal = 40;
double SEC = 3600;
double salper = count * (sal / SEC);
madeSoFar = String.valueOf(formatter.format(salper));
try {
mHandler.obtainMessage(1).sendToTarget();
Thread.sleep(1000);
seconds++;
count++;
} catch (InterruptedException e) {
e.printStackTrace();
}
if (killcheck) {
break;
}
}
// int length = count /360;
return null;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(Long result) {
}
}
#Override
public void onSaveInstanceState() {
// TODO Auto-generated method stub
Toast.makeText(this, "Activity state saved", Toast.LENGTH_LONG);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
checkedIN = savedInstanceState.getString("checkIN");
clicked = savedInstanceState.getBoolean("button");
Toast.makeText(this, "Activity state Restored", Toast.LENGTH_LONG);
}
#Override
public void onPause(Bundle b) {
// TODO Auto-generated method stub
b.putString("checkIN", checkedIN);
b.putBoolean("button", clicked);
Toast.makeText(this, "Activity state saved", Toast.LENGTH_LONG);
super.onPause();
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putString("checkIN", checkedIN);
outState.putBoolean("button", clicked);
Toast.makeText(this, "Activity state saved", Toast.LENGTH_LONG);
// etc.
super.onSaveInstanceState(outState);
}
#Override
protected void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Activity is getting killed", Toast.LENGTH_LONG)
.show();
}
}
You should not keep your Async task running in the background when your activity is send to the background. Your activity can be quit at any time so that you wouldn't have a reference to your activity anymore.
Regarding the preservation of state you could have a look at Activity.onRetainNonConfigurationInstance()

Text to speech doesn't seem to be working and there is no error message in logCat

There appears to be something wrong with this code, each time its saying that I have not installed texttoSpeech on create and I have done, also when i click the start read button the application crashed with no error messages... So heres the code..
public class CBrecipeReader extends Activity{
public Cursor cursor;
CBDataBaseHelper data;
public static int ReadData = 1;
public TextToSpeech Speak = null;
public boolean SpeakInit = false;
public TextView Speech;
public TextView rowIDText2;
CBListAdapter adapter;
String RowID;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.texttospeech);
Bundle extras = getIntent().getExtras();
Button StartSpeech = (Button)findViewById(R.id.startSpeech);
rowIDText2 = (TextView)findViewById(R.id.rowID2);
Speech = (TextView) findViewById(R.id.sayThis);
if (extras != null) {
RowID = extras.getString("SELECTED3");
rowIDText2.setText(RowID);
}
if (rowIDText2.getText() != ""){
data = new CBDataBaseHelper(this);
String s = rowIDText2.getText().toString();
int ID = Integer.parseInt(s);
data.open();
Cursor cursor = data.fetchRow(ID);
if (cursor.moveToFirst()){ // data?
Speech.setText(cursor.getString(1) + " " + cursor.getString(2) + " " + cursor.getString(3));
}
data.close();
}
//+ " " + cursor.getString(2) + "" + cursor.getString(3)
initSpeak();
speakButtons(StartSpeech);
}
protected void initSpeak(){
Intent intent = new Intent(Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(intent, ReadData);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if (requestCode == ReadData){
if (resultCode == Engine.CHECK_VOICE_DATA_PASS){
Speak = new TextToSpeech(this, new OnInitListener() {
public void onInit(int status) {
// TODO Auto-generated method stub
if (status == TextToSpeech.SUCCESS){
SpeakInit = true;
if(Speak.isLanguageAvailable(Locale.UK) >= 0){
Speak.setLanguage(Locale.UK);
Speak.setPitch(0.8f);
Speak.setSpeechRate(1.1f);
}
}
}
});
}else {
Intent installVoice = new Intent(Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installVoice);
}
}
}
protected void speakButtons(View view){
boolean diditwork;
try {
Speech = (TextView) findViewById(R.id.sayThis);
if (Speak != null && SpeakInit){
Speak.speak("test", TextToSpeech.QUEUE_ADD, null);
} else if (SpeakInit == false){
Toast.makeText(getApplicationContext(), "No Text to speech Installed ", Toast.LENGTH_SHORT).show();
}
}catch(Exception e){
diditwork = false;
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("darn");
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
}
}
}
Your code appears to be very similar to mine, the only difference I can see is
I call:
Speak.speak("test", TextToSpeech.QUEUE_FLUSH, null);
You call:
Speak.speak("test", TextToSpeech.QUEUE_ADD, null);

Categories

Resources