Android is confusing the functions of 3 different buttons - java

I'm currently making an app that will play some music.
There will be multiple activities, one for each song. There are usually 3 buttons per screen: One to play/pause the music, one for going to the previous page, and one for going to the next page.
Currently, Android is confused about which buttons are supposed to do what. When I click on the 'Play Music' button, the app attempts to take me to the next screen. When I click on the 'Next Page' button, it brings me to the previous page. When I click on the 'Last Page' button, it plays/pauses the song.
This is my java code for the relevant activity.
package net.jacksonhamilton.calmingmusic;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.view.View.OnClickListener;
import android.widget.TextView;
public class Rush extends Activity {
Button btnRush, btnRushtoCivil, btnRushtoNeil;
MediaPlayer tomsawyer;
int playing;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rush);
btnRush = (Button) findViewById(R.id.btnRush);
btnRushtoCivil = (Button) findViewById(R.id.btnRushtoCivil);
btnRushtoNeil = (Button) findViewById(R.id.btnRushtoNeil);
btnRush.setOnClickListener(btRush);
btnRushtoCivil.setOnClickListener(btRushtoCivil);
btnRushtoNeil.setOnClickListener(btRushtoNeil);
tomsawyer = new MediaPlayer();
tomsawyer = MediaPlayer.create(this, R.raw.tomsawyer);
playing = 0;
// TODO Auto-generated method stub
}
Button.OnClickListener btRush = new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (playing) {
case 0:
tomsawyer.start();
playing = 1;
btnRush.setText("Pause 'Tom Sawyer', by Rush");
break;
case 1:
tomsawyer.pause();
playing = 0;
btnRush.setText("Play 'Tom Sawyer', by Rush");
break;
}
}
};
Button.OnClickListener btRushtoCivil = new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
tomsawyer.stop();
startActivity(new Intent(Rush.this, Splash.class));
}
};
Button.OnClickListener btRushtoNeil = new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
tomsawyer.stop();
startActivity(new Intent(Rush.this, Neilyoung.class));
}
};
}
I've checked the IDs in the XML layout file, both graphically and in code. All buttons are assigned the proper IDs and the proper string value (for the text on the buttons).
I have the app set to require SDK15 as the minimum, and it is targeted to SDK19. It is also compiling with SDK19.
If it matters, I am developing the app in Eclipse Mars.
If you'd like to see the app for reference, here is a picture of the Activity.

You must have messed something up in the layout file, or you may be running some old version of the app. It sometimes happens in Eclipse that it does not rebuild the app but starts a last built version instead. Try deleting the app from the device/emulator, restarting the emulator, cleaning project or restarting IDE.

Related

R library in Android error

I have been using this Android Guide
While it has been a pleasant experience so far, I am experiencing my first problem. I copied all the code from the source that is in the link, and pasted it to the project folder, replacing all old files. Before starting to understand what I had pasted, I thought it would be logical to run the code first to check for problems. The project wouldn't run because of an R object missing. After importing it (Eclipse's solution to the problem), more errors popped up. I tried searching for an answer, both on the Internet and in the book, but to no avail. Since my software is up to date, I doubt this is a problem on the software's side. And since the code is available online, I think the problem would have popped up and been fixed.
Thank you in advance for the help. For extra details please ask in the comments.
The code:
MainActivity.java
package com.dummies.android.silentmodetoggle;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends Activity {
private AudioManager mAudioManager;
private boolean mPhoneIsSilent;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mAudioManager = (AudioManager)getSystemService(AUDIO_SERVICE);
checkIfPhoneIsSilent();
setButtonClickListener();
Log.d("SilentModeApp", "This is a test");
}
private void setButtonClickListener() {
Button toggleButton = (Button)findViewById(R.id.toggleButton);
toggleButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (mPhoneIsSilent) {
// Change back to normal mode
mAudioManager
.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
mPhoneIsSilent = false;
} else {
// Change to silent mode
mAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
mPhoneIsSilent = true;
}
// Now toggle the UI again
toggleUi();
}
});
}
/**
* Checks to see if the phone is currently in silent mode.
*/
private void checkIfPhoneIsSilent() {
int ringerMode = mAudioManager.getRingerMode();
if (ringerMode == AudioManager.RINGER_MODE_SILENT) {
mPhoneIsSilent = true;
} else {
mPhoneIsSilent = false;
}
}
/**
* Toggles the UI images from silent
* to normal and vice versa.
*/
private void toggleUi() {
ImageView imageView =
(ImageView) findViewById(R.id.phone_icon);
Drawable newPhoneImage;
if (mPhoneIsSilent) {
newPhoneImage =
getResources().getDrawable(R.drawable.phone_silent);
} else {
newPhoneImage =
getResources().getDrawable(R.drawable.phone_on);
}
imageView.setImageDrawable(newPhoneImage);
}
#Override
protected void onResume() {
super.onResume();
checkIfPhoneIsSilent();
toggleUi();
};
}
Try cleaning your project, this will rebuild your R file. If there is still no R file in your file-tree then you may have an error in one your xml layout files. Eclipse may not tell you this so be vigilant and check through all the files in the /res folder. Also, never import R when this happens.
Did you check if there is a variable named action_settings in /res/values/string.xml if it does not exist please create one and then clean using projects -> clean makesure that build Automatically is checked

Where to put activity code?

so I have a code that checks something and I put it in the onCreate() of an Activity. I want to know if it's correct to put it there and also, for some reason the code that checks the Main Activity doesn't work at all, the second one which has a toast works. I think the problem may be in an AlertDialog. Here's the one with the toast:
AlertDialog.Builder Dial = new AlertDialog.Builder(Screen.this);
Dial.setTitle(R.string.Dial_Tit);
Dial.setMessage(R.string.Dial_Mes);
Dial.setPositiveButton("OK", PosBC());
Dial.setNegativeButton(R.string.Dial_NegBC, NegBC());
Dial.show();
Note: both buttons have methods, I just didn't post them. The problem is that the alert doesn't even show. And also for some reason the toast does work, it like automatically clicks thebutton, even thought the method has an intent which doesn't work.
More code as requested:
private DialogInterface.OnClickListener NegBC() {
Intent moveToStart;
moveToStart = new Intent(Screen.this, Launch.class);
startActivity(moveToStart);
return null;
}
private DialogInterface.OnClickListener PosBC() {
startActivity(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS));
Toast.makeText(getApplicationContext(), R.string.settingsToast, Toast.LENGTH_LONG).show();
return null;
}
Update: I've added the create() method which shows the dialog but it goes like this : when activity is created shows toast, press back goes to settings, press back from settings shows dialog, buttons don't work.
onCreate() will be called whenever you start the application and if it is not cached in the device's RAM.
I do not understand what you are trying to achieve other than that, please edit your post by adding more of your code and I will also edit my answer to be more detailed.
use this code to display alertDialog in android on clicking a button:
package .....; // name of your package.
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class AlertDialogActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnAlertTwoBtns = (Button) findViewById(R.id.button1);
btnAlertTwoBtns.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// Creating alert Dialog with two Buttons
AlertDialog.Builder alertDialog = new AlertDialog.Builder(AlertDialogActivity.this);
// Setting Dialog Title
alertDialog.setTitle(" "); //type your title here insid the quotes.
// Setting Dialog Message
alertDialog.setMessage(" "); //type the message which is to be displayed
// Setting Icon to Dialog
alertDialog.setIcon(R.drawable.ic_launcher); // set the icon from drawable folder just put the icon file in drawable folder.
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
// Write your code here to execute after dialog
Toast.makeText(getApplicationContext(), "You clicked on YES", Toast.LENGTH_SHORT).show(); // just a sample code to tell that what things you can do here
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog
Toast.makeText(getApplicationContext(), "You clicked on NO", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
});
}
}
Write your AlertDialog code in OnCreateDialog and Start a in OnCreate AsynTask for Checking purpose and once your task is finished, inside onPostExecute close the Dialog.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showDialog(0x01);
}
#Override
protected Dialog onCreateDialog(int id) {
AlertDialog.Builder Dial;
switch (id) {
case 0x01:
Dial = new AlertDialog.Builder(Screen.this);
Dial.setTitle(R.string.Dial_Tit);
Dial.setMessage(R.string.Dial_Mes);
Dial.setPositiveButton("OK", PosBC());
Dial.setNegativeButton(R.string.Dial_NegBC, NegBC());
Dial.create();
break;
default:
break;
}
return super.onCreateDialog(id);
}
Ok, I solved it myself, turns out it was just logic missing :D. Sorry!

Android Development: Passing a parameter into an onClickListener()

Basically I am creating buttons within a for loop, I need each button to return a different value when pressed.
I had thought that creating my own onClickListener() and passing in the data needed as a parameter when it is initialized would work. It appears there are no syntax errors with what I came up with but when a button is clicked at run time the app crashes.
Heres a simplified version of what I've got thus far.
int counter = 1;
for( Program element : someList)
{
//some other code for dynamically creating textviews to stick the buttons in
//code which creates the buttons on the fly
moreInfo = new Button(this);
moreInfo.setText("More Info");
moreInfo.setOnClickListener(new DynamicOnClickListener(counter));
counter++;
}
The custom listener class
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
public class DynamicOnClickListener implements OnClickListener
{
int counter;
public DynamicOnClickListener(int acounter) {
this.counter = acounter;
}
public void onClick(View v) {
Log.v("DynamicOnClickListener","1");
Toast.makeText(v.getContext(), counter, Toast.LENGTH_LONG).show();
}
}
So in theory if this worked each button would return a different number, hope that makes sense.
Toast.makeText takes string resource id as a second argument. Your counter value is not a valid resource id that's way you are getting an error. You need to pass a String instead of int and it will work.
Toast.makeText(v.getContext(), String.valueOf(counter), Toast.LENGTH_LONG).show();
Instead of creating multiple listeners you can use setTag()
moreInfo = new Button(this);
moreInfo.setText("More Info");
moreInfo.setTag(new Integer(counter));
moreInfo.setOnClickListener(new DynamicOnClickListener();
then, in your listener
public void onClick(View v) {
Log.v("DynamicOnClickListener","1");
Toast.makeText(v.getContext(), ((Integer)v.getTag()).toString(), Toast.LENGTH_LONG).show();
}

Force closes caused by onClickListener

I made just one activity that opens another activity. Everything was working right until i setted up onClickListener. Now my app force closes when it launch. Without these two lines application launches correctly:
BUeasycounter.setOnClickListener(this);
BUrps.setOnClickListener(this);
Here is my full source:
package com.dano.learning;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Menu extends Activity implements View.OnClickListener{
Button BUeasycounter;
Button BUrps;
#Override
protected void onCreate(Bundle MyBundle) {
super.onCreate(MyBundle);
setContentView(R.layout.activity_main);
initializeVars();
// next 2 lines cause the problem
BUeasycounter.setOnClickListener(this);
BUrps.setOnClickListener(this);
}
public void initializeVars(){
Button BUeasycounter= (Button) findViewById(R.id.BUeasycounter);
Button BUrps = (Button) findViewById(R.id.BUrps);
}
public void onClick(View v) {
switch (v.getId()){
case R.id.BUeasycounter:
Intent openEasyCounter = new Intent("com.dano.learning.EASYCOUNTER");
startActivity(openEasyCounter);
break;
case R.id.BUrps:
Intent openRPS = new Intent("com.dano.learning.EASYCOUNTER");
startActivity(openRPS);
break;
};
}
}
Maybe i just typed something wrong but I cant find mistake in my source for more than two days. Thank you for your help.
There is no exception stack in question, but based on code I see one issue is:
Button BUeasycounter;
Button BUrps;
Both are pointing to null which could be throwing NullPointerException when you do
BUeasycounter.setOnClickListener(this);
BUrps.setOnClickListener(this);
Remove new variable in initializeVars method.
Example:
public void initializeVars(){
BUeasycounter= (Button) findViewById(R.id.BUeasycounter);
BUrps = (Button) findViewById(R.id.BUrps);
}
Note: Java naming convention suggest that use small letter as first letter for variable name.
remove smi-colon after swich case :
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()){
case R.id.BUeasycounter:
Intent openEasyCounter = new Intent("com.dano.learning.EASYCOUNTER");
startActivity(openEasyCounter);
break;
case R.id.BUrps:
Intent openRPS = new Intent("com.dano.learning.EASYCOUNTER");
startActivity(openRPS);
break;
} //>>>> from here remove semi-colon
and change initializeVars method as :
public void initializeVars(){
BUeasycounter= (Button) findViewById(R.id.BUeasycounter);
BUrps = (Button) findViewById(R.id.BUrps);
}
public void initializeVars(){
Button BUeasycounter= (Button) findViewById(R.id.BUeasycounter);
Button BUrps = (Button) findViewById(R.id.BUrps);
}
You define two button in this method but these are local variable whose scope lies between this block.
You can not access outside from this. You have initialize the local variable but instance button variable
still have null.To get solution from NPE you should write as
public void initializeVars(){
BUeasycounter= (Button) findViewById(R.id.BUeasycounter);
BUrps = (Button) findViewById(R.id.BUrps);
}
From above method it assign the reference in instance variable its scope till this class exist.
and last remove semi colon from end of switch block.

How To: Voice Commands into an android application

There are many tutorials online for adding voice recognition to an android app. They are often confusing and the publishers of the coding are never available for questions. I need a basic overview of how to add voice recognition to my app (as an answer, not a link).
If you want to add voice recognition to your group's Android app it is very simple.
Throughout this tutorial you will need to add imports as you paste in the code.
Create an xml file or use an existing one and make sure that you add a button and a listview.
In a java class you need to extend activity and implement OnClickListener
You will get an error that says you have unimplemented methods. Hover over it and add the unimplemented methods. We will add to this later.
Next set up the button and listview in your java.
public ListView mList;
public Button speakButton;
also add:
public static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
Next, make an OnCreate Method and set up the button and listener.
speakButton = (Button) findViewById(R.id.btn_speak);
speakButton.setOnClickListener(this);
also add this method(we will set it up next)
voiceinputbuttons();
Remember to setContentView for the xml you are showing.
Outside of your oncreate make a new method that looks like this.
public void voiceinputbuttons() {
speakButton = (Button) findViewById(R.id.btn_speak);
mList = (ListView) findViewById(R.id.list);
}
Now you will have to set up your voice recognition activity by using the following code.
public void startVoiceRecognitionActivity() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
"Speech recognition demo");
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
}
Next, inside your onclick method from step 2 add the activity from step 6.
startVoiceRecognitionActivity();
Next we will have to set up another method. Copy and paste the following code.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {
ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
mList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, matches));
matches is the result of voice input. It is a list of what the user possibly said. Using an if statement for the keyword you want to use allows the use of any activity if keywords match it is possible to set up multiple keywords to use the same activity so more than one word will allow the user To use the activity (makes it so the user doesn't have to memorize words from a list) To use an activity from the voice input information simply use the following format;
if (matches.contains("information")) {
informationMenu();
}
NOTE: you can format the code any time by pressing ctrl+shift+F in eclipse.
Now we are going to set up our method used by the code in step 8. This code creates an intent to direct the user to a new menu. You will need another xml and java class for this. Also, remember to add an activity to your manifest.
public void informationMenu() {
startActivity(new Intent("android.intent.action.INFOSCREEN"));
}
Finally you need to set up some code that will let the user know if the mic is operational. Paste this code inside of the OnCreate method at the end.
// Check to see if a recognition activity is present
// if running on AVD virtual device it will give this message. The mic
// required only works on an actual android device
PackageManager pm = getPackageManager();
List activities = pm.queryIntentActivities(new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (activities.size() != 0) {
voiceButton.setOnClickListener(this);
} else {
voiceButton.setEnabled(false);
voiceButton.setText("Recognizer not present");
}
FINAL NOTE: Voice Recognition will not work on a virtual emulator because they can't access the mic on your computer. The voice recognition will only work with an internet connection.
This is approx. what your final code should look like in your java.
package com.example.com.tutorialthread;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.speech.RecognizerIntent;
import android.support.v4.app.NavUtils;
public class main extends Activity implements OnClickListener {
public ListView mList;
public Button speakButton;
public static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
speakButton = (Button) findViewById(R.id.btn_speak);
speakButton.setOnClickListener(this);
voiceinputbuttons();
}
public void informationMenu() {
startActivity(new Intent("android.intent.action.INFOSCREEN"));
}
public void voiceinputbuttons() {
speakButton = (Button) findViewById(R.id.btn_speak);
mList = (ListView) findViewById(R.id.list);
}
public void startVoiceRecognitionActivity() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
"Speech recognition demo");
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
}
public void onClick(View v) {
// TODO Auto-generated method stub
startVoiceRecognitionActivity();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {
// Fill the list view with the strings the recognizer thought it
// could have heard
ArrayList matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
mList.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, matches));
// matches is the result of voice input. It is a list of what the
// user possibly said.
// Using an if statement for the keyword you want to use allows the
// use of any activity if keywords match
// it is possible to set up multiple keywords to use the same
// activity so more than one word will allow the user
// to use the activity (makes it so the user doesn't have to
// memorize words from a list)
// to use an activity from the voice input information simply use
// the following format;
// if (matches.contains("keyword here") { startActivity(new
// Intent("name.of.manifest.ACTIVITY")
if (matches.contains("information")) {
informationMenu();
}
}
}
Really good tutorial. Well done.
To complete a little bit more :
You need to add permission to your manifest as follow
<uses-permission android:name="android.permission.RECORD_AUDIO" />
Also voice does not work if you have
launchMode="singleInstance" or launchMode="singleTask" it looks like it should be "standard"

Categories

Resources