Hi,everyone!
I have a question- how to make all the buttons work, like the button with its ID "button"?
There are 10 buttons (button, button2,3,5,6,7,8,9,10,11) and 10 sounds (bark, bark 2,3,5,6,7,8,9,10,11)
activity code^
[SRC JAVA]package com.example.drums.candydrums;
import android.app.Activity;
import android.media.AudioManager;
import android.media.SoundPool;
import android.media.SoundPool.OnLoadCompleteListener;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
public class MainActivity extends Activity implements OnTouchListener {
private SoundPool soundPool;
private int soundID;
boolean loaded = false;
/** Called when the activity is first created. */
@override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View view = findViewById(R.id.button);
View view2 = findViewById(R.id.button2);
View view3 = findViewById(R.id.button3);
View view5 = findViewById(R.id.button5);
View view6 = findViewById(R.id.button6);
View view7 = findViewById(R.id.button7);
View view8 = findViewById(R.id.button8);
View view9 = findViewById(R.id.button9);
View view10 = findViewById(R.id.button10);
View view11 = findViewById(R.id.button11);
view.setOnTouchListener(this);
view2.setOnTouchListener(this);
view3.setOnTouchListener(this);
view5.setOnTouchListener(this);
view6.setOnTouchListener(this);
view7.setOnTouchListener(this);
view8.setOnTouchListener(this);
view9.setOnTouchListener(this);
view10.setOnTouchListener(this);
view11.setOnTouchListener(this);
// Set the hardware buttons to control the music
this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
// Load the sound
soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
@override
public void onLoadComplete(SoundPool soundPool, int sampleId,
int status) {
loaded = true;
}
});
soundID = soundPool.load(this, R.raw.bark, 1);
}
@override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
// Getting the user sound settings
AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
float actualVolume = (float) audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC);
float maxVolume = (float) audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float volume = actualVolume / maxVolume;
// Is the sound loaded already?
if (loaded) {
soundPool.play(soundID, volume, volume, 1, 0, 1f);
Log.e("Test", "Played sound");
}
}
if (event.getAction() == MotionEvent.ACTION_UP) {
}
return true;
}
}[/SRC]
Related
Hi y'all. I have recently been trying to make a calculator app in AS. However, the app stops when I click the calculate button. I also wanted to have it notify the user the result contained in the result variable, but the setContentText doesn't want to work. Code:
Code:
package firstapp.stars.com.firstapp;
import android.os.Bundle;
import android.app.Notification;
import android.app.NotificationManager;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class AddScrn extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
final Button button4;
button4 = (Button) findViewById(R.id.button4);
button4.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
TextView textView4 = (TextView) findViewById(R.id.textView4);
EditText editText7 = (EditText) findViewById(R.id.editText7);
EditText editText8 = (EditText) findViewById(R.id.editText8);
String mynum1=editText7.getText().toString();
String mynum2=editText8.getText().toString();
int result = Integer.parseInt(mynum1) + Integer.parseInt(mynum2);
textView4.setText(Integer.toString(result));
textView4.setText(result);
Notification notification = new Notification.Builder(getApplicationContext())
.setContentTitle("Calculator - Calculation result:")
String content = String.valueOf(result);
.setContentText(content);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// hide the notification after its selected
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_add_scrn, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Help.
Whats-a-username? said:
Hi y'all. I have recently been trying to make a calculator app in AS. However, the app stops when I click the calculate button. I also wanted to have it notify the user the result contained in the result variable, but the setContentText doesn't want to work. Code:
Code:
package firstapp.stars.com.firstapp;
import android.os.Bundle;
import android.app.Notification;
import android.app.NotificationManager;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class AddScrn extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
final Button button4;
button4 = (Button) findViewById(R.id.button4);
button4.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
TextView textView4 = (TextView) findViewById(R.id.textView4);
EditText editText7 = (EditText) findViewById(R.id.editText7);
EditText editText8 = (EditText) findViewById(R.id.editText8);
String mynum1=editText7.getText().toString();
String mynum2=editText8.getText().toString();
int result = Integer.parseInt(mynum1) + Integer.parseInt(mynum2);
textView4.setText(Integer.toString(result));
textView4.setText(result);
Notification notification = new Notification.Builder(getApplicationContext())
.setContentTitle("Calculator - Calculation result:")
String content = String.valueOf(result);
.setContentText(content);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// hide the notification after its selected
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_add_scrn, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Help.
Click to expand...
Click to collapse
Regarding the following code:
textView4.setText(Integer.toString(result));
textView4.setText(result);
Why you assign the value twice?
The first assignment is OK, but the second one need to removed.
The result variable is an Integer type, and when you assign Integer to TextView, it will look for a sting resource id (in the strings xml).
If the id is not found, it can throw an exception.
Yes, but the app still crashes when the button is clicked and still doesn't want to notify me.
Still Active Errors
1. In the setContentTitle it says" ; expected", but when ; is placed, it highlights everything.
2. "Cannot resolve method setContentText".
Whats-a-username? said:
1. In the setContentTitle it says" ; expected", but when ; is placed, it highlights everything.
2. "Cannot resolve method setContentText".
Click to expand...
Click to collapse
Your code is incorrect.
Change you code to the following:
String content = String.valueOf(result);
Notification notification = new Notification.Builder(this)
.setContentTitle("Calculator - Calculation result:")
.setContentText(content).build();
Can you help me. I have developed a app with a quiz. When the quiz is finished a new activity (result) appears showing the score. I want to pass the score to a new activity namely score. Here is my code. What is wrong. The score must be showed in a textview.
Result.java
Code:
package app.mobiledevicesecurity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Result extends Activity
{
private static Button playbtn;
private static Button menubutton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
OnClickPlayButtonListener();
OnClickMenuButtonListener();
TextView textResult = (TextView) findViewById(R.id.textResult);
Bundle b = getIntent().getExtras();
int score = b.getInt("score");
textResult.setText("You scored" + " " + score + " for the quiz.");
Intent i = new Intent(getApplicationContext(), Result.class);
i.putExtra("somevariable",score);
startActivity(i);
}
public void OnClickPlayButtonListener() {
playbtn = (Button) findViewById(R.id.btn);
playbtn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("app.mobiledevicesecurity.Quiz");
startActivity(intent);
}
}
);
}
public void OnClickMenuButtonListener() {
menubutton = (Button) findViewById(R.id.menubtn);
menubutton.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
}
);
}
Scores.java
Code:
package app.mobiledevicesecurity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.content.Intent;
public class Scores extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scores);
Intent intent = getIntent();
String value = intent.getStringExtra("somevariable");
TextView txtScore1 = (TextView) findViewById(R.id.txtScore1);
txtScore1.setText("You scored" + " " + value + " for the quiz.");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_scores, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Try this
In Result.java
i.putExtra("somevariable",score);alter this code like below..
i.putExtra("somevariable", score.toString());
you are passing integer and getting as string..try to pass it as string may help
or simply change this in scores.java
String value = intent.getStringExtra("somevariable")alter this code like below
Int value = intent.getIntExtra("somevariable")
Sent from my SM-N900 using XDA Free mobile app
As noted by taku_coder you are sending and int then you try to extract a String at least be consistent if you want to send an int then extract as an int on your receiving Activity.
Also i noted that the that you are sending the value to Result Activity shouldnt it be the Scores Activity?
Intent i = new Intent(getApplicationContext(), Result.class);
i.putExtra("somevariable",score);
startActivity(i);
Shouldnt it be like this?
Intent i = new Intent(getApplicationContext(), Scores.class);
i.putExtra("somevariable",score);
startActivity(i);
In Result.java
intent.putExtra("KeyName",X.toString());
you are passing as string, you can get it by using
intent.getextra("KeyName")
Intent i = new Intent(getApplicationContext(), Result.class);
i.putExtra("somevariable",score);
startActivity(i);
It seems to be the code above in OnCreate() method of Result make recursive creation of Result class.
Hello, I am new to the app making world and a pretty bad coder while we're at it.
my bmi calculator crashes on launch in the emulator.
here is my code:
package com.gilad_inc.myapplication;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
EditText height, weight;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
makwork();
ConvertDouble();
}
public void makwork()
{
height = (EditText) findViewById(R.id.Height);
weight = (EditText) findViewById(R.id.Weight);
}
public void ConvertDouble()
{
EditText height = this.height;
EditText weight = this.weight;
Double H = Double.parseDouble(height.getText().toString());
Double W = Double.parseDouble(weight.getText().toString());
}
public void buttonOnClick(View v) {
makwork();
ConvertDouble();
float h = Float.valueOf(height.getText().toString());
float w = Float.valueOf(weight.getText().toString());
/***
* Time for math!
* BMI is calculated
* (weigth in kg / (height in meter * height in meter)
* But since we want the user to input in CM, we just
* multiply it with 10 000 to get the correct value.
*/
double BMI = w / (h * h) * 10000;
TextView tvBMI = (TextView) findViewById(R.id.BMI);
tvBMI.setText("" + BMI);
}
@override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
how can I prevent it from crashing?
When i run my script below everything works fine. When i want to go back to the previous activity i get a black screen on the emulator and then the app shuts down, i also get a black screen when i exit the application and try to resume it.
The script:
Code:
package com.example.bono.as3;
import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import java.io.IOException;
import java.io.InputStream;
public class Main extends Activity {
DrawView drawView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
drawView = new DrawView(this);
setContentView(drawView);
}
@Override public void onResume(){
super.onResume();
drawView.resume();
}
@Override public void onPause(){
super.onPause();
drawView.pause();
}
public class DrawView extends SurfaceView implements Runnable{
Thread gameloop = new Thread();
SurfaceHolder surface;
volatile boolean running = false;
AssetManager assets = null;
BitmapFactory.Options options = null;
Bitmap incect[];
int frame = 0;
public DrawView(Context context){
super(context);
surface = getHolder();
assets = context.getAssets();
options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
incect = new Bitmap[2];
try {
for (int n = 0; n < incect.length; n++){
String filename = "incect"+Integer.toString(n+1)+".png";
InputStream istream = assets.open(filename);
incect[n] = BitmapFactory.decodeStream(istream,null,options);
istream.close();
}
} catch (IOException e){
e.printStackTrace();
}
}
public void resume(){
running = true;
gameloop = new Thread(this);
gameloop.start();
}
public void pause(){
running = false;
while (true){
try {
gameloop.join();
}
catch (InterruptedException e){}
}
}
@Override public void run (){
while (running){
if (!surface.getSurface().isValid())
continue;
Canvas canvas = surface.lockCanvas();
canvas.drawColor(Color.rgb(85, 107, 47));
canvas.drawBitmap(incect[frame], 0, 0, null);
surface.unlockCanvasAndPost(canvas);
frame++;
if (frame > 1) frame = 0;
try {
Thread.sleep(500);
} catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
}
I dont get any error message in the log, what i do get is about 13 messages saying "suspending all threads took: X ms" so it has something to the with my gameloop Thread i think. Unfortunately i dont see what the problem is in my code... Can anyone help me with this?
I am new in javascript and android studio. Im trying to learn how to combine this 2 coding into one to get the accelerometer and gyro readings running on 1 app. The top code is for the accelerometer. The bottom is for the gyro.
HTML:
package com.example.mzr.accelerometer;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Vibrator;
import android.widget.TextView;
public class MainActivity extends Activity implements SensorEventListener {
private float lastX, lastY, lastZ;
private SensorManager sensorManager;
private Sensor accelerometer;
private float deltaXMax = 0;
private float deltaYMax = 0;
private float deltaZMax = 0;
private float deltaX = 0;
private float deltaY = 0;
private float deltaZ = 0;
private float vibrateThreshold = 0;
private TextView currentX, currentY, currentZ, maxX, maxY, maxZ;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeViews();
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
if (sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null) {
// success! we have an accelerometer
accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
vibrateThreshold = accelerometer.getMaximumRange() / 2;
} else {
// fai! we dont have an accelerometer!
}
//initialize vibration
}
public void initializeViews() {
currentX = (TextView) findViewById(R.id.currentX);
currentY = (TextView) findViewById(R.id.currentY);
currentZ = (TextView) findViewById(R.id.currentZ);
maxX = (TextView) findViewById(R.id.maxX);
maxY = (TextView) findViewById(R.id.maxY);
maxZ = (TextView) findViewById(R.id.maxZ);
}
//onResume() register the accelerometer for listening the events
protected void onResume() {
super.onResume();
sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
//onPause() unregister the accelerometer for stop listening the events
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
[user=439709]@override[/user]
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
[user=439709]@override[/user]
public void onSensorChanged(SensorEvent event) {
// clean current values
displayCleanValues();
// display the current x,y,z accelerometer values
displayCurrentValues();
// display the max x,y,z accelerometer values
displayMaxValues();
// get the change of the x,y,z values of the accelerometer
deltaX = Math.abs(lastX - event.values[0]);
deltaY = Math.abs(lastY - event.values[1]);
deltaZ = Math.abs(lastZ - event.values[2]);
// if the change is below 2, it is just plain noise
if (deltaX < 2)
deltaX = 0;
if (deltaY < 2)
deltaY = 0;
if ((deltaX > vibrateThreshold) || (deltaY > vibrateThreshold) || (deltaZ > vibrateThreshold)) {
}
}
public void displayCleanValues() {
currentX.setText("0.0");
currentY.setText("0.0");
currentZ.setText("0.0");
}
// display the current x,y,z accelerometer values
public void displayCurrentValues() {
currentX.setText(Float.toString(deltaX));
currentY.setText(Float.toString(deltaY));
currentZ.setText(Float.toString(deltaZ));
}
// display the max x,y,z accelerometer values
public void displayMaxValues() {
if (deltaX > deltaXMax) {
deltaXMax = deltaX;
maxX.setText(Float.toString(deltaXMax));
}
if (deltaY > deltaYMax) {
deltaYMax = deltaY;
maxY.setText(Float.toString(deltaYMax));
}
if (deltaZ > deltaZMax) {
deltaZMax = deltaZ;
maxZ.setText(Float.toString(deltaZMax));
}
}
}
HTML:
package com.example.mzr.gyro;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView textX, textY, textZ;
SensorManager sensorManager;
Sensor sensor;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensor = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
textX = (TextView) findViewById(R.id.maxX);
textY = (TextView) findViewById(R.id.maxY);
textZ = (TextView) findViewById(R.id.maxZ);
}
public void onResume() {
super.onResume();
sensorManager.registerListener(gyroListener, sensor,
SensorManager.SENSOR_DELAY_NORMAL);
}
public void onStop() {
super.onStop();
sensorManager.unregisterListener(gyroListener);
}
public SensorEventListener gyroListener = new SensorEventListener() {
public void onAccuracyChanged(Sensor sensor, int acc) { }
public void onSensorChanged(SensorEvent event) {
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
textX.setText("X : " + (int)x + " rad/s");
textY.setText("Y : " + (int)y + " rad/s");
textZ.setText("Z : " + (int)z + " rad/s");
}
};
}