Using two Buttons on one Activity - button

I'm still new to android. I have a kids book that l have done with two buttons "READ TO ME" and "READ TO MYSELF".
Read to me onclick will play a recording as it reads the book but it goes to SoundOne Activity.
Read to myself will display text and it leads to PageOne Activity.
How do l create some sort of an "if statement" such that when l click read to me it will play the recording but lead to PageOne Activity. And when l click read to myself it will display the text but still leads to PageOne Activity
This might help reduce the number of classes l have created so far and avoid ANR l assume. Some source code or a tutorial will help Thanks in advance my code is below:
package com.inerds.donkiejoukie;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.content.Context;
public class Fbone extends MainActivity {
MediaPlayer one;
MediaPlayer mb;
MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.fbone);
one = MediaPlayer.create(this, R.raw.pageone);
mb = MediaPlayer.create(this, R.raw.menubar);
mp = MediaPlayer.create(this, R.raw.pageflip);
ImageButton imageButton1 = (ImageButton) findViewById(R.id.imageButton1);
imageButton1.setOnClickListener (new OnClickListener() {
public void onClick(View vone) {
mb.pause();
mb.stop();
mp.start();
startActivity(new Intent(getApplicationContext(), PageOne.class));
finish();
}
});
ImageButton readtome = (ImageButton) findViewById(R.id.readtome);
readtome.setOnClickListener (new OnClickListener() {
public void onClick(View v) {
mb.pause();
mb.stop();
one.start();
startActivity(new Intent(getApplicationContext(), SoundOne.class));
AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 100, 0);
finish();
}
});
}
}

The Intent mechanism is used to communicate from one Activity to another. In the Intent, as well as a class to start, you can specify the name of an action to perform, as well as other options. In this case, you might want to use an extra to tell the following class whether to play sound or not. When you start the intent:
Intent nextActivity = new Intent(getApplicationContext(), SoundOne.class);
// Put true or false in the next line according to which click handler you're in.
nextActivity.putBooleanExtra(SoundOne.extra_enableSound, true);
startActivity(nextActivity);
and then in your SoundOne activity, you need a constant field for the extra name:
static final String extra_enableSound = "enableSound";
and you can find the value of this extra from your onCreate, or wherever you want to start the sound:
if (getIntent().getBooleanExtra(extra_enableSound, false)) {
// start the sound
}
Now your PageOne activity is unused and can be deleted. The documentation for Intent tells you what other information you can stash in there.

I'm not a professional programmer so this might not be the best way to do this, but it works well for me with minimal code.
Here's what I'm doing.
Set an "onClick" for the buttons in my XML
<Button
android:id="#+id/button2"
android:layout_width="144dp"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/button1"
android:onClick="sendMessage1"
android:text="#string/cancel"
/>
the in the activity i set up my buttons
Button button1;
Button button2;
then use a sendmessage instead of onButtonclick
public void sendMessage(View view)
{
Intent intent = new Intent(this, ThirdActivity.class);
startActivity(intent);
}
public void sendMessage1(View view)
{
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}

package com.inerds.donkiejoukie;
public class Fbone extends MainActivity {
MediaPlayer one;
MediaPlayer mb;
MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fbone);
one = MediaPlayer.create(this, R.raw.pageone);
mb = MediaPlayer.create(this, R.raw.menubar);
mp = MediaPlayer.create(this, R.raw.pageflip);
ImageButton imageButton1 = (ImageButton) findViewById(R.id.imageButton1);
ImageButton readtome = (ImageButton) findViewById(R.id.readtome);
imageButton1.setOnClickListener (handleOnClickListener);
readtome.setOnClickListener (handleOnClickListener);
}
private OnClickListener handleOnClickListener = new OnClickListener() {
public void onClick(View v) {
switch(v.getId()){
case R.id.imageButton1:
mb.pause();
mb.stop();
mp.start();
startActivity(new Intent(getApplicationContext(), PageOne.class));
finish();
break;
case R.id.readtome:
mb.pause();
mb.stop();
one.start();
startActivity(new Intent(getApplicationContext(), SoundOne.class));
AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 100, 0);
finish();
break;
}
}
};
}

Related

How can I change the scene By pressing a specific key(b) on the the keyboard?

In my application, there are two scenes: mainScene and bossScene where mainScene is used when starting up the application.
I'm trying to implement the boss key functionality where by pressing the 'b' key on the the keyboard should change the scene to bossScene. And also by pressing the button in bossScene should switch back to mainScene.
I'm getting an error on InteliJ saying "Cannot resolve method setOnKeyPressed in List
My Code:
public void start(Stage stage) throws Exception {
stage.setTitle("BossKey Example");
// Scene and layout for the main view
VBox root = new VBox();
Scene mainScene = new Scene(root, 500, 300);
// Scene for the BOSS view
Scene bossScene = new Scene(new Label("Nothing suspicious here"), 500, 300);
List<TextField> fields = new ArrayList<TextField>();
for (int i = 0; i < 10; i++) {
fields.add(new TextField());
}
fields.setOnKeyPressed(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent keyEvent) {
switch (keyEvent.getCharacter()){
case "b": stage.setScene(bossScene); break;
}
}
});
/////// Added addEventFilter, still not working
mainScene.addEventFilter(KeyEvent.KEY_PRESSED, new
EventHandler<KeyEvent() {
#Override
public void handle(KeyEvent keyEvent) {
switch (keyEvent.getCharacter()){
case "b": stage.setScene(bossScene); break;
}
keyEvent.consume();
}
});
// Create components for main view
root.getChildren().addAll(fields);
root.getChildren().add(new Button("Hello!"));
stage.setScene(mainScene);
stage.show();
}
}
KeyCombination filters
You should use a key combination in an event filter, e.g., CTRL+B or SHORTCUT+B.
For details on how to apply key combinations, see:
javafx keyboard event shortcut key
Why a key combination is superior to filtering on the character "b":
If you filter on a "b" character, the feature won't work if caps lock is down.
If you filter on a "b" character, you will be unable to type "b" in the text field.
You might think you could write scene.setOnKeyPressed(...), however, that won't work as expected in many cases. A filter is required rather than a key press event handler because the key events may be consumed by focused fields like text fields if you use a handler, so a handler implementation might not activate in all desired cases.
Filtering on a key combination avoids the issues with trying to handle a character key press. The key combinations rely on key codes which represent the physical key pressed and don't rely on the state of other keys such as caps lock unless you explicitly add additional logic for that.
If you don't understand the difference between an event filter and an event handler and the capturing and bubbling phases of event dispatch, then study:
the oracle event handling tutorial.
KeyCombination filter implementation
final EventHandler<KeyEvent> bossEventFilter = new EventHandler<>() {
final KeyCombination bossKeyCombo = new KeyCodeCombination(
KeyCode.B,
KeyCombination.CONTROL_DOWN
);
public void handle(KeyEvent e) {
if (bossKeyCombo.match(e)) {
if (stage.getScene() == mainScene) {
stage.setScene(bossScene);
} else if (stage.getScene() == bossScene) {
stage.setScene(mainScene);
}
e.consume();
}
}
};
mainScene.addEventFilter(KeyEvent.KEY_PRESSED, bossEventFilter);
bossScene.addEventFilter(KeyEvent.KEY_PRESSED, bossEventFilter);
Accelerator alternative
An accelerator could be used instead of an event filter. Information on applying an accelerator is also in an answer to the linked question, I won't detail this alternative further here.
Example Solution
Standalone executable example code:
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.input.*;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import java.io.IOException;
public class SceneSwap extends Application {
#Override
public void start(Stage stage) throws IOException {
final Scene mainScene = new Scene(
createLayout(
"Press CTRL+B to enter boss mode",
Color.PALEGREEN
)
);
final Scene bossScene = new Scene(
createLayout(
"Press CTRL+B to exit boss mode",
Color.PALEGOLDENROD
)
);
final EventHandler<KeyEvent> bossEventFilter = new EventHandler<>() {
final KeyCombination bossKeyCombo = new KeyCodeCombination(
KeyCode.B,
KeyCombination.CONTROL_DOWN
);
public void handle(KeyEvent e) {
if (bossKeyCombo.match(e)) {
if (stage.getScene() == mainScene) {
stage.setScene(bossScene);
} else if (stage.getScene() == bossScene) {
stage.setScene(mainScene);
}
e.consume();
}
}
};
mainScene.addEventFilter(KeyEvent.KEY_PRESSED, bossEventFilter);
bossScene.addEventFilter(KeyEvent.KEY_PRESSED, bossEventFilter);
stage.setScene(mainScene);
stage.show();
}
private VBox createLayout(String text, Color color) {
VBox mainLayout = new VBox(10,
new Label(text),
new TextField()
);
mainLayout.setPadding(new Insets(10));
mainLayout.setStyle("-fx-background: " + toCssColor(color));
return mainLayout;
}
private String toCssColor(Color color) {
int r = (int) Math.round(color.getRed() * 255.0);
int g = (int) Math.round(color.getGreen() * 255.0);
int b = (int) Math.round(color.getBlue() * 255.0);
int o = (int) Math.round(color.getOpacity() * 255.0);
return String.format("#%02x%02x%02x%02x" , r, g, b, o);
}
public static void main(String[] args) {
launch();
}
}

Can anyone till me how to make a button In libgdx

Hi can anyone tell me how to make a click able button​In Libgdx
For a mobile device that does something if you touch it
This is a minimal example of what you are trying to achieve with comments
package com.mygdx.gtest;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
public class Test extends ApplicationAdapter{
private Skin skin;
private TextButton button;
private Stage stage;
#Override
public void create() {
//make a stage for your button to go on
stage = new Stage();
//load a skin(a collection of styles for objects)
// skin is from gdx-skins (https://github.com/czyzby/gdx-skins)
skin = new Skin(Gdx.files.internal("neon-ui.json"));
//create your button
button = new TextButton("Button1", skin);
//add it to your stage
stage.addActor(button);
// add a listener to your buttons so it does something when clicked
button.addListener(new ChangeListener() {
#Override
public void changed(ChangeEvent event, Actor actor) {
System.out.println("I was clicked");
}
});
// set the sgae as the input processor so it will respond to clicks etc
Gdx.input.setInputProcessor(stage);
}
#Override
public void render() {
//clear the screen
Gdx.gl.glClearColor(0.3f, 0.3f, 0.3f, 1f);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
// tell stage to do action and then draw itself
stage.draw();
stage.act();
}
}
This is how you can add a Button without adding any external skin
TextButton.TextButtonStyle textButtonStyle = new TextButton.TextButtonStyle();
textButtonStyle.font = yourCustomFont;
textButtonStyle.fontColor = Color.WHITE;
stage.add(new TextButton("Custom Btn ", textButtonStyle));

samsung gear live audio encoding

I'm currently working on an Android Wear app, and I'm looking toward audio recording. I've followed the tutorial on the Android developper website, and it works well on my Nexus 7, but not on the Samsung Gear Live I have for testing. The application just goes crashing all the time.
Digging a bit into the problem, I might have figured out that it was a problem with 2 parameters for the recorder to work: either the OutputFormat, or the AudioEncoder. I tried pairing and trying all the OutputFormat and AudioEncoder available, but without any luck.
So here's my question: did someone encounter the same problem? And if so, did you find the right combination of Format/Encoder?
I don't paste my code as it's exactly the same as in the documentation. Here is the link if you want to have a look: http://developer.android.com/guide/topics/media/audio-capture.html
Thank you in advance for your answers and your time :)
The root problem is that you cannot use MediaRecorder, even though the Android audio capture example does, but instead you need to use the AudioRecord class.
Also, I'd recommend streaming the raw data back to your phone to assemble it into an audio file as that is very thorny on a wearable.
For more, see this answer for more.
I have included a sample below that I got working.
import android.app.Activity;
import android.content.Intent;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.support.wearable.view.WatchViewStub;
import android.util.Log;
import android.widget.TextView;
import android.view.View;
import java.util.List;
public class MainActivity extends Activity {
private static final String TAG = MainActivity.class.getName();
private static final int SPEECH_REQUEST_CODE = 1;
private static final int RECORDER_SAMPLERATE = 44100;
private static final int RECORDER_CHANNELS = AudioFormat.CHANNEL_IN_STEREO;
private static final int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT;
private TextView mTextView;
private AudioRecord recorder;
private int bufferSize = 0;
private Thread recordingThread = null;
private volatile boolean isRecording;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.v(TAG, "Creating MainActivity");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
#Override
public void onLayoutInflated(WatchViewStub stub) {
mTextView = (TextView) stub.findViewById(R.id.text);
}
});
bufferSize =
AudioRecord.getMinBufferSize(RECORDER_SAMPLERATE,
RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING);
}
public void handleRecordButtonClick(View view) {
startAudioCapture();
}
public void handleStopButtonClick(View view) {
stopAudioCapture();
}
private void startAudioCapture() {
Log.v(TAG, "Starting audio capture");
recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,
RECORDER_SAMPLERATE, RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING, bufferSize);
if (recorder.getState() == AudioRecord.STATE_INITIALIZED) {
recorder.startRecording();
isRecording = true;
Log.v(TAG, "Successfully started recording");
recordingThread = new Thread(new Runnable() {
#Override
public void run() {
processRawAudioData();
}
}, "AudioRecorder Thread");
recordingThread.start();
} else {
Log.v(TAG, "Failed to started recording");
}
}
private void stopAudioCapture() {
Log.v(TAG, "Stop audio capture");
recorder.stop();
isRecording = false;
recorder.release();
}
private void processRawAudioData() {
byte data[] = new byte[bufferSize];
int read = 0;
while(isRecording) {
read = recorder.read(data, 0, bufferSize);
if(AudioRecord.ERROR_INVALID_OPERATION != read) {
Log.v(TAG, "Successfully read " + data.length + " bytes of audio");
}
}
}
}

how to use progressbar when loading image in picasso?

I want onStart() method to load image from server using picasso and I want to show a progress bar until the photos are fully downloaded
Here is my code:
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
Picasso.with(context).load(imageLoad)
.placeholder(R.id.progressBarDetails)
.error(R.drawable.friend_request).noFade().resize(200, 200)
.into(avatarImage, new Callback() {
#Override
public void onError() {
// TODO Auto-generated method stub
}
#Override
public void onSuccess() {
// TODO Auto-generated method stub
progressbar.setVisibility(View.GONE);
}
});
Picasso.with(this).load(imageLoad).into(target);
}
OnFinished a = new OnFinished() {
#Override
public void onSendFinished(IntentSender IntentSender, Intent intent,
int resultCode, String resultData, Bundle resultExtras) {
// TODO Auto-generated method stub
intent = new Intent(getApplicationContext(), Map.class);
}
};
private Target target = new Target() {
#Override
public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
new Thread(new Runnable() {
#Override
public void run() {
File file = new File(Environment
.getExternalStorageDirectory().getPath()
+ "/actress_wallpaper.jpg");
try {
file.createNewFile();
FileOutputStream ostream = new FileOutputStream(file);
bitmap.compress(CompressFormat.JPEG, 75, ostream);
ostream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
I haven't tested your code but even if that works, the file actress_wallpaper.jpg isn't loaded in the ImageView. In the docs, it says
Objects implementing this class must have a working implementation of Object.equals(Object) and Object.hashCode() for proper storage internally.
Try this:
File file = new File(pathToFile);
Picasso.with(context)
.load(file)
.into(imageView, new Callback() {
#Override
public void onSuccess() {
progressbar.setVisibility(View.GONE);
}
});
be warned I haven't tested my code.
Update:
I have tried version 2.3.2 and 2.3.3, it seems like that there's an issue https://github.com/square/picasso/issues/539
It is an old question but may be this answer can help others as I also had issues in showing progress bar while loading image from server.
I am using Picasso 2.4.0. and I am using Picasso Target interface to load image in imageview. Here is the tested and working code:
First add the following lines:
ImageView ivPhoto = (ImageView) findViewById(R.id.iv_photo);
ProgressBar pbLoadingBar = (ProgressBar) findViewById(R.id.pb_loading_bar);
//get image url
String imageUrl = getImageUrl();
//ImageViewTarget is the implementation of Target interface.
//code for this ImageViewTarget is in the end
Target target = new ImageViewTarget(ivPhoto, pbLoadingBar);
Picasso.with(mContext)
.load(imageUrl)
.placeholder(R.drawable.place_holder)
.error(R.drawable.error_drawable)
.into(target);
Here is the implementation of Target interface used above
private static class ImageViewTarget implements Target {
private WeakReference<ImageView> mImageViewReference;
private WeakReference<ProgressBar> mProgressBarReference;
public ImageViewTarget(ImageView imageView, ProgressBar progressBar) {
this.mImageViewReference = new WeakReference<>(imageView);
this.mProgressBarReference = new WeakReference<>(progressBar);
}
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
//you can use this bitmap to load image in image view or save it in image file like the one in the above question.
ImageView imageView = mImageViewReference.get();
if (imageView != null) {
imageView.setImageBitmap(bitmap);
}
ProgressBar progressBar = mProgressBarReference.get();
if (progressBar != null) {
progressBar.setVisibility(View.GONE);
}
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
ImageView imageView = mImageViewReference.get();
if (imageView != null) {
imageView.setImageDrawable(errorDrawable);
}
ProgressBar progressBar = mProgressBarReference.get();
if (progressBar != null) {
progressBar.setVisibility(View.GONE);
}
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
ImageView imageView = mImageViewReference.get();
if (imageView != null) {
imageView.setImageDrawable(placeHolderDrawable);
}
ProgressBar progressBar = mProgressBarReference.get();
if (progressBar != null) {
progressBar.setVisibility(View.VISIBLE);
}
}
}
The above code works fine if used for loading image in activity. But if you want to load image in gridview/recyclerview or view pager etc. where same view holder is used, you might get an issue where onBitmapLoaded() is not called (as the view is recycled and Picasso only keeps a weak reference to the Target object). Here is a link to solve this problem.
change to this
Picasso.get()
.load(tImageUrl())
.into(holder.AnimImage, new Callback() {
#Override
public void onSuccess() {
holder.progressBar.setVisibility(View.GONE);
}
#Override
public void onError(Exception e) {
}
});

How to send message to mute sound through activities

As the title, I want to mute sound when hitting X button or unmute when hitting Y button, and I want to keep this status through activities. Here is my code.
When hitting X button:
mSound.setVolume(0, 0);
sound = "SOUND_OFF";
Y button:
mSound.setVolume(1, 1);
sound = "SOUND_ON"
When I finish my first activity:
Intent i = new Intent(getApplicationContext(),com.example.englishtest.Question.class);
i.putExtra("checkSound", sound);
startActivity(i);
overridePendingTransition(R.anim.right_in, R.anim.left_out);
finish();
In my second activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
Bundle extras = getIntent().getExtras();
if(extras != null) {
sound = extras.getString("checkSound");
checkVolume(sound);
}
My checkVolume function:
public void checkVolume(String s){
if(s=="SOUND_ON"){
mSound.setVolume(1, 1);
}
else if(s=="SOUND_OFF"){
mSound.setVolume(0, 0);
}
}
But it doesn't work. Can anyone show me my mistake?
Too late from the moment you post this question. But I think your approaching is bad.
Let create another class with a static field to hold configuration status.
Such as:
public class Configuration {
public static boolean soundOn;
}
Initialize this field in the main Activity:
protected void onCreate(Bundle savedBundle) {
Configuration.soundOn = true;
...
}
Then just checking this field whenever you wanna setVolume and remember to save new status to this field when setting mute/unmute from any activity.

Resources