I am trying to play a sound on button click and I am trying to make it call the .start() function only but the problem is I set the i parameter in the onclick function and so it does not pass the i to the onclicklistner function any ideas how to fix that ??
here is my code
package com.example.buttonsdemo;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.support.v4.widget.SimpleCursorAdapter.ViewBinder;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity implements View.OnClickListener{
//Creating Sound arrays
int i=0;
MediaPlayer[] mediaplayer = new MediaPlayer[120];
Button button[] = new Button [120];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Initialize the mediaplayer
for(int z=0;z<120;z++)
{
mediaplayer[z]=null;
}
//Initialize Button Array
for(int x=0;x<120;x++)
{
button[x]=new Button(this);
button[x].setOnClickListener(this);
}
//Creating Media player array
mediaplayer[0]= MediaPlayer.create(this,R.raw.akali);
mediaplayer[1]= MediaPlayer.create(this,R.raw.alistar);
button[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.akali:
i=0;
break;
case R.id.alistar:
i=1;
break;
}
mediaplayer[i].start();
}
} );
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
Inside your Listener, you want to use a variable which is declared inside your Listener.
You are trying to use a variable (i) which is declared in code which is not run when the Listener is run.
new View.OnClickListener() {
#Override
public void onClick(View v) {
int idx;
switch(v.getId()) {
case R.id.akali:
idx=0;
break;
case R.id.alistar:
idx=1;
break;
}
mediaplayer[idx].start();
}
}
Or invoke the respective start() method right in the case.
Dump the 'i' declared. Replace method with this (the "Button theButton" needs to stay 'final').
for(int z=0;z<120;z++)
{
final Button theButton = button[z];
theButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
// TODO Auto-generated method stub
// do what you want.
}
});
}
I believe your onCreate should be created like this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Initialize the mediaplayer
for(int z=0;z<120;z++)
{
mediaplayer[z]=null;
}
mediaplayer[0]= MediaPlayer.create(this,R.raw.akali);
mediaplayer[1]= MediaPlayer.create(this,R.raw.alistar);
//Initialize Button Array
for( x=0;x<120;x++)
{
button[x]=new Button(this);
button[x].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaplayer[x].start();
}
} );
}
}
So basically you just need to make several button on the fly which produces different sound when clicked. Try this code:
Button myButton[] = new Button[100];
MediaPlayer mySound = new MediaPlayer();
for (int i=0; i<100; i++) {
myButton[i] = new Button(this);
myButton[i].setId(i+1);
myButton[i].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Resources res = context.getResources();
int soundId = res.getIdentifier("sound" + v.getId(), "raw", context.getPackageName());
mySound.create(getApplicationContext(), soundId);
mySound.start();
}
});
}
Related
This is the line i want to repeat.
handler.postDelayed(runnableCode, 1);
This app is a tycoon app and so the user can buy upgrades and if they tap the button the get $$ and so when they buy upgrades keeping the value up-to-date is required.
package com.example.navjeevenmann.mytycoon;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private Button myButton;
private int Counter = 0;
private Button myButton2;
private TextView myTextView;
Handler handler = new Handler();
private int Test = 5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler.postDelayed(runnableCode, 1);
myButton = (Button) findViewById(R.id.button);
myButton2 = (Button) findViewById(R.id.button2);
myTextView = (TextView) findViewById(R.id.textView);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ButtonCounter(Counter);
}
});
myButton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(),
SecondActivity.class);
intent.putExtra("Count", Counter);
startActivity(intent);
finish();
}
});
}
public int ButtonCounter(int Counter){
Counter+=1;
return Counter;
}
public int AutoCounter(int Counter, int add) {
Counter+=add;
return Counter;
}
public void Display(int Counter, TextView myTextView) {
String man = String.valueOf(Counter);
myTextView.setText("$" + man);
}
private Runnable runnableCode = new Runnable() {
#Override
public void run() {
// Do something here on the main thread
Counter = AutoCounter(Counter,Test);
Display(Counter, myTextView);
}
};
}
handler.postDelayed(runnableCode, 1);
call that line inside onResume() method. Make sure your show an AlertDialog to the user whenever he or she hits the button to get $$. Since the AlertDialog pops up everytime the user tries to buy $$. onResume() will be called.
Try this
private void startAnimation() {
countDownTimer = new CountDownTimer(700, 500) {
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
//your code to repeat
}
start();
}
}.start();
}
Android. i am a newbie I have 6 images. One image view, two buttons previous and next. Have written the program, but when executing, crashes. I have written the logic of how to change the images in image view, I have removed all the syntax errors. here is my Mainactivity.java code
package com.example.hm2_koppineedi;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends Activity {
ImageView imageView;
Button previous,next;
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
imageView= (ImageView)findViewById(R.id.imageView1);
previous = (Button)findViewById(R.id.button1);
previous.setOnClickListener((OnClickListener) this);
next = (Button)findViewById(R.id.button2);
next.setOnClickListener((OnClickListener) this);
}
public void onClick(View view)
{
int a=0;
switch (view.getId())
{
case R.id.button2:
if (a == 0)
{
imageView.setImageResource(R.drawable.hdimage);
a = 1;
}
else if (a == 1)
{
imageView.setImageResource(R.drawable.elephant);
a = 2;
}
else if (a == 2)
{
imageView.setImageResource(R.drawable.giraffe);
a = 3;
}
else if (a == 3)
{
imageView.setImageResource(R.drawable.horse);
a = 4;
}
else if (a == 4)
{
imageView.setImageResource(R.drawable.lion);
a = 5;
}
else if (a == 5)
{
imageView.setImageResource(R.drawable.tiger);
a = 6;
}
else if (a == 6)
break;
case R.id.button1:
a--;
button2.performClick();
next.performClick();
break;
}
}
}
Wrong code:
previous.setOnClickListener((OnClickListener) this);
next.setOnClickListener((OnClickListener) this);
Use this:
previous.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//...
}
);
next.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//...
}
);
I think you need to override the OnClick method, and make sure it is in your activity.
public class myActivity extends Activity {
...
#Override
public void onClick(View v) {
// Do something
}
...
}
You should not have to cast "this", but call...
setOnClickListener(this);
...from inside one of your activity methods (for instance : OnCreate), so that "this" be the activity. That way, all calls to "Click" in the context of your activity will be sent to your OnClick method.
You have lots of examples on this site to show that.
I am having a screen which has a WebView showing a UI developed in HTML and PHP. Now, when i migrate to a different screen in Android and want to come back to my parent screen, I want to have a NEW WebView layout. Even though I am passing a String variable back for validating purposes, but still then it does not work out. Does this have to do anything with the savedInstanceState? Any suggestions would be appreciated. Below is the code snippet.
package com.example.notifboard;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
public class AdminLogin extends Activity {
boolean flag = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
flag = true;
}
protected void onResume() {
super.onResume();
if (flag == true) {
setContentView(R.layout.adminloginmixed);
final Button AdminBtn = (Button)findViewById(R.id.AdminBtn);
final Button EventGenBtn = (Button)findViewById(R.id.EventGenBtn);
final Button BackBtn = (Button)findViewById(R.id.BackBtn);
AdminBtn.setBackgroundColor(Color.WHITE);
AdminBtn.setTextColor(Color.BLACK);
EventGenBtn.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
EventGenBtn.setBackgroundColor(Color.WHITE);
EventGenBtn.setTextColor(Color.BLACK);
AdminBtn.setBackgroundColor(Color.parseColor("#1D326B"));
AdminBtn.setTextColor(Color.WHITE);
BackBtn.setBackgroundColor(Color.parseColor("#1D326B"));
BackBtn.setTextColor(Color.WHITE);
Intent EveGenIntent = new Intent(AdminLogin.this, EventGen.class);
startActivity(EveGenIntent);
finish();
}
});
AdminBtn.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
EventGenBtn.setBackgroundColor(Color.parseColor("#1D326B"));
EventGenBtn.setTextColor(Color.WHITE);
BackBtn.setBackgroundColor(Color.parseColor("#1D326B"));
BackBtn.setTextColor(Color.WHITE);
AdminBtn.setBackgroundColor(Color.WHITE);
AdminBtn.setTextColor(Color.BLACK);
}
});
BackBtn.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
BackBtn.setBackgroundColor(Color.WHITE);
BackBtn.setTextColor(Color.BLACK);
EventGenBtn.setBackgroundColor(Color.parseColor("#1D326B"));
EventGenBtn.setTextColor(Color.WHITE);
AdminBtn.setBackgroundColor(Color.parseColor("#1D326B"));
AdminBtn.setTextColor(Color.WHITE);
Intent BackBtnIntent = new Intent(AdminLogin.this, SelectEntryType.class);
startActivity(BackBtnIntent);
finish();
}
});
WebView browser = (WebView)findViewById(R.id.Adminloginwebview);
browser.setWebViewClient(new WebViewClient());
browser.loadUrl("http://sivasphpmobileapps.site90.net/NotificationBoard/AdminLogin.php");
}
else {
setContentView(R.layout.adminloginmixed);
final Button AdminBtn = (Button)findViewById(R.id.AdminBtn);
final Button EventGenBtn = (Button)findViewById(R.id.EventGenBtn);
final Button BackBtn = (Button)findViewById(R.id.BackBtn);
AdminBtn.setBackgroundColor(Color.WHITE);
AdminBtn.setTextColor(Color.BLACK);
EventGenBtn.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
EventGenBtn.setBackgroundColor(Color.WHITE);
EventGenBtn.setTextColor(Color.BLACK);
AdminBtn.setBackgroundColor(Color.parseColor("#1D326B"));
AdminBtn.setTextColor(Color.WHITE);
BackBtn.setBackgroundColor(Color.parseColor("#1D326B"));
BackBtn.setTextColor(Color.WHITE);
Intent EveGenIntent = new Intent(AdminLogin.this, EventGen.class);
startActivity(EveGenIntent);
}
});
AdminBtn.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
EventGenBtn.setBackgroundColor(Color.parseColor("#1D326B"));
EventGenBtn.setTextColor(Color.WHITE);
BackBtn.setBackgroundColor(Color.parseColor("#1D326B"));
BackBtn.setTextColor(Color.WHITE);
AdminBtn.setBackgroundColor(Color.WHITE);
AdminBtn.setTextColor(Color.BLACK);
}
});
BackBtn.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
BackBtn.setBackgroundColor(Color.WHITE);
BackBtn.setTextColor(Color.BLACK);
EventGenBtn.setBackgroundColor(Color.parseColor("#1D326B"));
EventGenBtn.setTextColor(Color.WHITE);
AdminBtn.setBackgroundColor(Color.parseColor("#1D326B"));
AdminBtn.setTextColor(Color.WHITE);
Intent BackBtnIntent = new Intent(AdminLogin.this, SelectEntryType.class);
startActivity(BackBtnIntent);
}
});
WebView browser = (WebView)findViewById(R.id.Adminloginwebview);
browser.setWebViewClient(new WebViewClient());
browser.loadUrl("http://sivasphpmobileapps.site90.net/NotificationBoard/NewEvents.php");
}
}
}
I want to implement 2 activities , one is a listview with image and text which works well now. The other one is a onClicklistener when I click any ListItem it will start another activity to show more information, with 1 previous button and next button to see the Prev information or next. However there is something wrong with the button. It can only see the previous one and next one once. Which means you can't click the next button twice. Any suggestions will be appreciated .
Here is my main activity code
package com.example.manchesterunited;
import com.example.manchesterunited.R;
import android.os.Bundle;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Intent;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
static PlayerData data = new PlayerData();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CustomAdapter adapter = new CustomAdapter(this);
setListAdapter(adapter);
}
public void onListItemClick(ListView l,View v, int pos, long id){
int playerId = (int)id;
Toast.makeText(getApplicationContext(),"Selected "+data.getName(pos),Toast.LENGTH_SHORT).show();
Intent intent = new Intent(this, InfoActivity.class);
intent.putExtra("playerId", playerId);
startActivity(intent);
}
}
And here is the second activity
package com.example.manchesterunited;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class InfoActivity extends Activity {
TextView dobText;
TextView pobText;
TextView internationalText;
Button prevButton;
Button nextButton;
PlayerData data = new PlayerData();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_info);
dobText = (TextView)findViewById(R.id.textView1);
pobText = (TextView)findViewById(R.id.textView2);
internationalText = (TextView)findViewById(R.id.textView3);
prevButton = (Button)findViewById(R.id.prev);
nextButton = (Button)findViewById(R.id.next);
Intent intent = getIntent();
final int playerId = intent.getExtras().getInt("playerId");
dobText.setText("Birthdate:"+String.valueOf(data.getPlayer(playerId).getDob()));
pobText.setText("Birthplace:"+String.valueOf(data.getPlayer(playerId).getPob()));
internationalText.setText("International:"+data.getPlayer(playerId).getInternational());
prevButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int newId = playerId-1;
dobText.setText("Birthdate:"+String.valueOf(data.getPlayer(newId).getDob()));
pobText.setText("Birthplace:"+String.valueOf(data.getPlayer(newId).getPob()));
internationalText.setText("International:"+data.getPlayer(newId).getInternational());
}
});
nextButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int newId = playerId+1;
dobText.setText("Birthdate:"+String.valueOf(data.getPlayer(newId).getDob()));
pobText.setText("Birthplace:"+String.valueOf(data.getPlayer(newId).getPob()));
internationalText.setText("International:"+data.getPlayer(newId).getInternational());
}
});}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_info, menu);
return true;
}
}
You're not updating the playerID.
You're just getting a new ID.
you should put
int newId = playerId+1;
playerID = newId; //insert this line
so that when you click again,
playerID gets updated.
You are always adding just 1 to player ID which will now point to next item. But as soon as you re-click the button it will have the same player ID that was passed through intent. So again it will add in the same value. Make a new variable which will store the current player ID that is visible and keep on incrementing it then you will be able to browse next and vice versa in the previous case.
You can't increment player ID as it has been declared as final, so you can either make a global variable or put a variable in intent and increment it on button clicks.
nextButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
//make newId global then it will work. And keep on updating it when the button is clicked accordingly.
newId = playerId+1;
dobText.setText("Birthdate:"+String.valueOf(data.getPlayer(newId).getDob()));
pobText.setText("Birthplace:"+String.valueOf(data.getPlayer(newId).getPob()));
internationalText.setText("International:"+data.getPlayer(newId).getInternational());
}
});}
Try this on InfoActivity,
private int playerId;
...
...onCreate(...){
...
playerId = intent.getExtras().getInt("playerId");
prevButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
...
playerId--;
dobText.setText("Birthdate:"+String.valueOf(data.getPlayer(playerId).getDob()));
pobText.setText("Birthplace:"+String.valueOf(data.getPlayer(playerId).getPob()));
internationalText.setText("International:"+data.getPlayer(playerId).getInternational());
}
}
nextButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
...
playerId++;
dobText.setText("Birthdate:"+String.valueOf(data.getPlayer(playerId).getDob()));
pobText.setText("Birthplace:"+String.valueOf(data.getPlayer(playerId).getPob()));
internationalText.setText("International:"+data.getPlayer(playerId).getInternational());
}
}
}
I'm working on a simple game. The idea of the first round is that, there are 26 buttons (images) on the first activity - english alphabet and I want to make it pronounce on button click. For example, when I press "a" button, it must say "a". How can I get the ID of each button, then string of it and give it to speak() method as a parameter? THANKS IN ADVANCE !
Code is here:
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Vibrator;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;
import java.util.Locale;
import java.util.Random;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
public class FirstActivity extends Activity {
/** Called when the activity is first created. */
TextToSpeech ttx;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.firstact);
ttx = new TextToSpeech(
FirstActivity.this,
new TextToSpeech.OnInitListener() {
public void onInit(int status) {
// TODO Auto-generated method stub
if(status !=TextToSpeech.ERROR){
ttx.setLanguage(Locale.US);
}
}
});
TableLayout table = (TableLayout) findViewById(R.id.table);
String alphabet = "abcdefghijqlmnopqrstuvwxyz";
int pos = 0;
for (int i = 0; i < 7; i++) {
TableRow row = new TableRow(this);
for (int j = 0; j < 4; j++) {
if (pos == 26) {
break;
}
Button but = new Button(this);
/*but.setOnClickListener(btnListener);*/
but.setText(Character.toString(alphabet.charAt(pos++)));
but.setHeight(80);
but.setWidth(70);
but.setBackgroundResource(R.drawable.burti);
row.addView(but);
but.setId(pos);
but.setOnClickListener((OnClickListener) this);
table.addView(row);
}}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
if(ttx != null){
ttx.stop();
ttx.shutdown();
}
super.onPause();
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
String pressed = but.getText().toString(); //error here....
ttx.speak(pressed, TextToSpeech.QUEUE_FLUSH, null);
}
}
I made a working example: http://frank.anemaet.nl/android/TalkingButtons.zip
Here is a snippet of the working code:
for (int i = 0; i < alphabet.length(); i++)
{
TableRow row = new TableRow(this);
Button but;
but = new Button(this);
but.setText(Character.toString(alphabet.charAt(i)));
but.setHeight(button_width);
but.setWidth(button_height);
but.setId(i);
but.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
performClick(v);
}
});
row.addView(but);
table.addView(row);
}
...
public void performClick(View arg0){
Button tv = (Button)findViewById(arg0.getId());
String pressed = tv.getText().toString();
ttx.speak(pressed, TextToSpeech.QUEUE_FLUSH, null);
}
Your onInit() method has to do more, like handle when the user does not have the language data installed.
See this code for a helper class.