Repeating a random musical note in Android Studio - java

I've already made a button that when pressed goes into an array of notes and chooses one randomly, what I don't know how to do is have a button that replays that random note whenever pressed. I was thinking of using the rSound integer but since it's in a private void I can't use it.. How should i go about this?
Code:
package com.stefanawesome.piano;
import android.content.pm.ActivityInfo;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.Build;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
//Declaring variables and array:
ImageButton NoteNew;
ImageButton Repeat;
Button c, d, e, f, g, a, b, high;
List<Integer> soundList = new ArrayList<Integer>();
private SoundPool soundpool;
private int sound_c, sound_d, sound_e, sound_f, sound_g, sound_a, sound_b, sound_high;
//Random Note Function:
private void playRandomSound() {
int randomInt = (new Random().nextInt(soundList.size()));
int rSound = soundList.get(randomInt);
MediaPlayer mp = MediaPlayer.create(this, rSound);
mp.start();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
//Find View by ID all here:
soundList.add(R.raw.c);
soundList.add(R.raw.d);
soundList.add(R.raw.e);
soundList.add(R.raw.f);
soundList.add(R.raw.g);
soundList.add(R.raw.a);
soundList.add(R.raw.b);
soundList.add(R.raw.chigh);
NoteNew = (ImageButton) findViewById(R.id.Newnote);
Repeat = (ImageButton) findViewById(R.id.Repeat);
c = (Button) findViewById(R.id.C);
d = (Button) findViewById(R.id.D);
e = (Button) findViewById(R.id.E);
f = (Button) findViewById(R.id.F);
g = (Button) findViewById(R.id.G);
a = (Button) findViewById(R.id.A);
b = (Button) findViewById(R.id.B);
high = (Button) findViewById(R.id.high);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
soundpool = new SoundPool.Builder().setMaxStreams(5).build();
} else {
soundpool = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
}
//Soundpools over here:
sound_c = soundpool.load(this, R.raw.c, 1);
sound_d = soundpool.load(this, R.raw.d, 1);
sound_e = soundpool.load(this, R.raw.e, 1);
sound_f = soundpool.load(this, R.raw.f, 1);
sound_g = soundpool.load(this, R.raw.g, 1);
sound_a = soundpool.load(this, R.raw.a, 1);
sound_b = soundpool.load(this, R.raw.b, 1);
sound_high = soundpool.load(this, R.raw.chigh, 1);
//When button gets clicked do something:
c.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
soundpool.play(sound_c, 1, 1, 0, 0, 1);
}
});
d.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
soundpool.play(sound_d, 1, 1, 0, 0, 1);
}
});
e.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
soundpool.play(sound_e, 1, 1, 0, 0, 1);
}
});
f.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
soundpool.play(sound_f, 1, 1, 0, 0, 1);
}
});
g.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
soundpool.play(sound_g, 1, 1, 0, 0, 1);
}
});
a.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
soundpool.play(sound_a, 1, 1, 0, 0, 1);
}
});
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
soundpool.play(sound_b, 1, 1, 0, 0, 1);
}
});
high.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
soundpool.play(sound_high, 1, 1, 0, 0, 1);
}
});
NoteNew.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
playRandomSound();
}
});
}
}

Just save the random integer(which s the index of the random note) in some other variable.
Then, use that variable to replay the last random note.
Update your function to
int last;
private void playRandomSound() {
int randomInt = (new Random().nextInt(soundList.size()));
last=randomInt;
int rSound = soundList.get(randomInt);
MediaPlayer mp = MediaPlayer.create(this, rSound);
mp.start();
}
And add this new function(call it with new button)
private void playlastRandomSound() {
int rSound = soundList.get(last);
MediaPlayer mp = MediaPlayer.create(this, rSound);
mp.start();
}

Related

How to Delete an Item from Arraylist in SharedPreferences with Android Studio

I was trying to save the array's data in shared prefrences and two problems occured.
The first one is that every time I open the activity that should have the array in it (mainPage activity) it doesn't show anything until I add use the foodAdding activity to add food and then it shows all the previous foods and shows the food that I have just added
The second one is that whenever I try to delete any of the elements it get deleted till I refresh the activity or go to another activity and come back so how could I delete elements properly in the shared prefrences ??
the code for the mainPage activity (the activity that should show all the foods):
package com.example.yourhealthapp;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
public class mainPage extends AppCompatActivity {
Button adding;
Button main;
Button profile;
public static ArrayList<Food> foods = new ArrayList<Food>();
FoodAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_page);
adapter = new FoodAdapter(this, foods);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
Intent intent = getIntent();
int weight = intent.getIntExtra("weight", 404);
int height = intent.getIntExtra("height", 404);
int age = intent.getIntExtra("age", 404);
adding = findViewById(R.id.adding_main);
main = findViewById(R.id.main_main);
profile = findViewById(R.id.profile_main);
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
final int item = position;
new AlertDialog.Builder(mainPage.this).setIcon(android.R.drawable.ic_delete).setTitle("Are you sure ?").setMessage("Do you want to delete this meal ?")
.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
foods.remove(item);
adapter.notifyDataSetChanged();
}
})
.setNegativeButton("no", null).show();
return true;
}
});
adding.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent next_page = new Intent(mainPage.this, foodadding.class);
next_page.putExtra("weight", weight);
next_page.putExtra("height", height);
next_page.putExtra("age", age);
startActivity(next_page);
}
});
main.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent next_page = new Intent(mainPage.this, mainPage.class);
next_page.putExtra("weight", weight);
next_page.putExtra("height", height);
next_page.putExtra("age", age);
startActivity(next_page);
}
});
profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent next_page = new Intent(mainPage.this, profile.class);
next_page.putExtra("weight", weight);
next_page.putExtra("height", height);
next_page.putExtra("age", age);
startActivity(next_page);
}
});
loadData();
adapter.notifyDataSetChanged();
}
#Override
protected void onResume() {
super.onResume();
adapter.notifyDataSetChanged();
}
public void loadData()
{
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("meals list", null);
Type type = new TypeToken<ArrayList<Food>>() {}.getType();
foods = gson.fromJson(json, type);
if (foods == null)
{
foods = new ArrayList<>();
}
}
}
The code for the foodAdding activity (the activity that you add the foods from):
package com.example.yourhealthapp;
import androidx.appcompat.app.AppCompatActivity;
import android.app.SearchManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
public class foodadding extends AppCompatActivity {
Button adding;
Button main;
Button profile;
Button add;
Button dont;
EditText calories;
EditText servings;
EditText grams;
EditText name;
mainPage array = new mainPage();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_foodadding);
adding = findViewById(R.id.adding_food);
main = findViewById(R.id.main_food);
profile = findViewById(R.id.profile_food);
add = findViewById(R.id.add);
dont = findViewById(R.id.dont);
Intent i = getIntent();
int weight = i.getIntExtra("weight", 404);
int height = i.getIntExtra("height", 404);
int age = i.getIntExtra("age", 404);
grams = findViewById(R.id.grams);
calories = findViewById(R.id.calories);
servings = findViewById(R.id.servings);
name = findViewById(R.id.name);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Food w = new Food(name.getText().toString(), Integer.parseInt(calories.getText().toString()) , Integer.parseInt(servings.getText().toString()), Integer.parseInt(grams.getText().toString()));
array.foods.add(w);
saveData();
}
});
dont.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String q = name.getText().toString();
q = "How many calories there are in one serving of" + q;
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH );
intent.putExtra(SearchManager.QUERY, q);
startActivity(intent);
}
});
adding.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent next_page = new Intent(foodadding.this, foodadding.class);
next_page.putExtra("weight", weight);
next_page.putExtra("height", height);
next_page.putExtra("age", age);
startActivity(next_page);
}
});
main.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent next_page = new Intent(foodadding.this, mainPage.class);
next_page.putExtra("weight", weight);
next_page.putExtra("height", height);
next_page.putExtra("age", age);
startActivity(next_page);
}
});
profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent next_page = new Intent(foodadding.this, profile.class);
next_page.putExtra("weight", weight);
next_page.putExtra("height", height);
next_page.putExtra("age", age);
startActivity(next_page);
}
});
}
public void saveData()
{
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(array.foods);
editor.putString("meals list", json);
editor.apply();
}
}
And I want as well to save the info that I created using the user's input in this activity (profile) so how could I do that ?
the code for the profile activity is :
package com.example.yourhealthapp;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import java.lang.Math;
import android.widget.Button;
import android.widget.TextView;
public class profile extends AppCompatActivity {
Button adding;
Button main;
Button profile;
Button edit;
int caleaten = 0 ;
MainActivity info = new MainActivity();
mainPage fo = new mainPage();
TextView gain;
TextView loose;
TextView maintain;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
adding = findViewById(R.id.adding_profile);
main = findViewById(R.id.main_profile);
maintain = findViewById(R.id.maintain);
edit = findViewById(R.id.edit);
loose = findViewById(R.id.loosing);
gain = findViewById(R.id.gaining);
profile = findViewById(R.id.profile_profile);
Intent intent = getIntent();
int weight = intent.getIntExtra("weight", 404);
int height = intent.getIntExtra("height", 404);
int age = intent.getIntExtra("age", 404);
double maintanancem = (10 * weight) + (6.25 * height) - (5 * age) + 5;
double maintainancew = (10 * weight) + (6.25 * height) - (5 * age) - 161;
if(info.active == "low physical activity")
{
maintainancew *= 1.375;
maintanancem *= 1.375;
}
else if(info.active == "average physical activity")
{
maintainancew *= 1.550;
maintanancem *= 1.550;
}
else
{
maintainancew *= 1.725;
maintanancem *= 1.725;
}
for (int i = 0 ; i < fo.foods.size(); i++)
{
caleaten += fo.foods.get(i).getmCalories() * fo.foods.get(i).getmServings();
}
maintanancem -= caleaten;
maintainancew -= caleaten;
if (info.g == "male" )
{
maintain.setText(Integer.toString((int)maintanancem));
gain.setText(Integer.toString((int)maintanancem + 500));
loose.setText(Integer.toString((int) (maintanancem - 500)));
}
else
{
maintain.setText(Integer.toString((int)maintainancew));
gain.setText(Integer.toString((int)maintainancew + 500));
loose.setText(Integer.toString((int)maintainancew - 500));
}
adding.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent next_page = new Intent(profile.this, foodadding.class);
next_page.putExtra("weight", weight);
next_page.putExtra("height", height);
next_page.putExtra("age", age);
startActivity(next_page);
}
});
edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(profile.this , MainActivity.class);
startActivity(i);
}
});
main.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent next_page = new Intent(profile.this, mainPage.class);
next_page.putExtra("weight", weight);
next_page.putExtra("height", height);
next_page.putExtra("age", age);
startActivity(next_page);
}
});
profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent next_page = new Intent(profile.this, profile.class);
next_page.putExtra("weight", weight);
next_page.putExtra("height", height);
next_page.putExtra("age", age);
startActivity(next_page);
}
});
}
}

Preventing repeat answers Android

I've build an quiz app so I can practice myself with different question. I want to make sure that once I provides an answer for a particular question, the question get disable to prevent multiple answers being entered, as well I know it's in the Toast section but i'm looking to add a final score at the end in percentage. I would greatly appreciate some help.
package com.example.randomuser.androidquiz;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
public class QuizActivity extends AppCompatActivity {
private Button mTrueButton;
private Button mFalseButton;
private ImageButton mNextButton;
private ImageButton mPreviousButton;
private TextView mQuestionTextView;
private int mCurrentIndex = 0;
private static final String KEY_INDEX = "index";
private Question[] mQuestionBank = new Question[] {
new Question(R.string.quiz_questionone, false),
new Question(R.string.quiz_questiontwo, true),
new Question(R.string.quiz_questionthree, true),
new Question(R.string.quiz_questionfour, false),
new Question(R.string.quiz_questionfive, true),
new Question(R.string.quiz_questionsix, false),
new Question(R.string.quiz_questionseven, true),
new Question(R.string.quiz_questioneight, false),
new Question(R.string.quiz_questionnine, false),
new Question(R.string.quiz_questionten, true),
new Question(R.string.quiz_questionelevn, false),
new Question(R.string.quiz_questiontwelve, false),
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
if(savedInstanceState != null)
{
mCurrentIndex = savedInstanceState.getInt(KEY_INDEX, 0);
}
mQuestionTextView = (TextView) findViewById(R.id.question_textview);
updateQuestion();
mQuestionTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mCurrentIndex = (mCurrentIndex + 1)% mQuestionBank.length;
updateQuestion();
}
});
mNextButton = (ImageButton) findViewById(R.id.next_button);
mNextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick( View view ) {
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
updateQuestion();
}
});
mPreviousButton = (ImageButton) findViewById(R.id.previous_button);
mPreviousButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick( View view ) {
mCurrentIndex = (mCurrentIndex - 1) % mQuestionBank.length;
if(mCurrentIndex < 0){
mCurrentIndex = 0;
}
updateQuestion();
}
});
mFalseButton = (Button) findViewById(R.id.falseButton);
mFalseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
checkAnswer(false);
}
});
mTrueButton = (Button) findViewById(R.id.trueButton);
mTrueButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
checkAnswer(true);
}
});
}
private void updateQuestion() {
int question = mQuestionBank[mCurrentIndex].getTextResId();
mQuestionTextView.setText(question);
}
private void checkAnswer(boolean userGuess)
{
boolean a = mQuestionBank[mCurrentIndex].isAnswer();
int messageId = 0;
if(userGuess == a)
{
messageId = R.string.right_answer;
}
else{
messageId = R.string.wrong_answer;
}
Toast toast= Toast.makeText(QuizActivity.this, messageId, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP, 0, 300);
toast.show();
}
#Override
protected void onSaveInstanceState( Bundle outState ) {
super.onSaveInstanceState(outState);
outState.putInt(KEY_INDEX, mCurrentIndex);
}
}

Sound when counter reaches specific time? Android

first of all pardon my English, but I think it's understandable.
So in this app is a counter and I need it to do sound when it reaches for example 30 seconds.
note: this is my first question here so if I broke any rules or I could have asked better way, let me know please
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;
public class MainActivity extends AppCompatActivity {
private Button mStartButton;
private Button mPauseButton;
private Button mResetButton;
private Chronometer mChronometer;
private long lastPause;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mStartButton = (Button) findViewById(R.id.start_button);
mPauseButton = (Button) findViewById(R.id.pause_button);
mResetButton = (Button) findViewById(R.id.reset_button);
mChronometer = (Chronometer) findViewById(R.id.chronometer);
mStartButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (lastPause != 0){
mChronometer.setBase(mChronometer.getBase() + SystemClock.elapsedRealtime() - lastPause);
}
else{
mChronometer.setBase(SystemClock.elapsedRealtime());
}
mChronometer.start();
mStartButton.setEnabled(false);
mPauseButton.setEnabled(true);
}
});
mPauseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
lastPause = SystemClock.elapsedRealtime();
mChronometer.stop();
mPauseButton.setEnabled(false);
mStartButton.setEnabled(true);
}
});
mResetButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mChronometer.stop();
mChronometer.setBase(SystemClock.elapsedRealtime());
lastPause = 0;
mStartButton.setEnabled(true);
mPauseButton.setEnabled(false);
}
});
}
}
Define global integer variable as counter and count it in Chronometer's OnChronometerTickListener, and when it reach for example 30 then play sound and reset your counter:
int c = -1; // define global
chronometer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
#Override
public void onChronometerTick(Chronometer chronometer) {
c++;
if(c == 30) {
c = 0;
MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.ding);
mp.start();
}
}
});

Android studio use same integer in 2 activities

i was making an android app and i need to use one integer value in 2 activities. I tried using this code but it didn't work.
//Integer Sender
Intent myIntent = new Intent(A.this, B.class);
myIntent.putExtra("MyIntNameGoesHere", intValue);
startActivity(myIntent);
//Integer receiver
Intent mIntent = getIntent();
int intValue = mIntent.getIntExtra("intVariableName", 0);
It says Cannot resolve symbol intValue and Cannot resolve symbol A and the same for B.
Here's the whole code.
MainActivity:
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int balance;
private SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Hide notification bar
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
//Click counter
final TextView text = (TextView) findViewById(R.id.balance_text);
assert text != null;
// to retreuve the values from the shared preference
preferences = PreferenceManager.getDefaultSharedPreferences(this);
balance = preferences.getInt("balance", 0);
text.setText(balance + " $");
final ImageButton button = (ImageButton) findViewById(R.id.click_button);
assert button != null;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
balance++;
text.setText("" + balance + " $");
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("balance", balance);
editor.apply();
}
});
final Button UpgradesButton = (Button) findViewById(R.id.upgrades_button);
assert UpgradesButton != null;
UpgradesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, UpgradesActivity.class));
}
});
//Balance Integer Sender
}
}
UpgradesActivity:
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
public class UpgradesActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upgrades);
//Hide notification bar
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
final Button e2u_button = (Button) findViewById(R.id.e2u_button);
assert e2u_button != null;
e2u_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
final Button back_button = (Button) findViewById(R.id.back_button);
assert back_button != null;
back_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(UpgradesActivity.this, MainActivity.class));
}
});
//TODO: Pass balance integer from MainActivity to here.
}
}
Error code:
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
public class UpgradesActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upgrades);
//Receive balance from MainActivity
Intent mIntent = getIntent();
int intValue = mIntent.getIntExtra("key_int", 0);
//Hide notification bar
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
final Button e2u_button = (Button) findViewById(R.id.e2u_button);
assert e2u_button != null;
e2u_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(balance >= 300){ //ERROR ON THIS LINE
}
}
});
final Button back_button = (Button) findViewById(R.id.back_button);
assert back_button != null;
back_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(UpgradesActivity.this, MainActivity.class));
}
});
//TODO: Pass balance integer from MainActivity to here.
}
}
ALL ABOVE IS ANSWERED! ---------------------------------------------------------
Now i have problems with this part of the code:
#Override
public void onClick(View v) {
if(balance >= 300){
balance -= 300;
}
if(balance < 300){
final TextView text = (TextView) findViewById(R.id.not_enough_money_text);
assert text != null;
text.setText("You do not have enough money.");
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
text.setText("");
}
}, 2000);
}
}
When i click the button it says i do not have enough money but i have over 300. Please help me.
I found out what the problem was but I'm not sure how to fix it. I need to send balance back to MainActivity. Can anyone help with that?
Send the data like this -
UpgradesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, UpgradesActivity.class);
intent.putExtra("key_int", balance);
startActivity(intent);
}
});
And fetch it in onCreate() of UpgradesActivity -
Intent mIntent = getIntent();
int intValue = mIntent.getIntExtra("key_int", 0);
You're using different key when sending and receiving the Int.
Change this line:
int intValue = mIntent.getIntExtra("intVariableName", 0);
To this:
int intValue = mIntent.getIntExtra("MyIntNameGoesHere", 0);

The values are not being passed on the first click of editText

I need to take the values of a and b from the user via editText and pass it to the next activity.This is the first activity:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.content.Intent;
import android.widget.EditText;
public class activitysecond extends AppCompatActivity {
private String[] arraySpinner;
private String[] arraySpinner2;
int a=0,b=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondactivity);
final EditText editText1=(EditText) findViewById(R.id.editText1);
final EditText editText2=(EditText) findViewById(R.id.editText2);
final Bundle bundle = new Bundle();
Button EnterButton=(Button) findViewById(R.id.Enterbutton);
this.arraySpinner = new String[]{
"None", "Lightly Active", "Moderately Active", "Very Active"
};
Spinner s = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> adapter = new ArrayAdapter<>
(this,
android.R.layout.simple_spinner_dropdown_item, arraySpinner
);
s.setAdapter(adapter);
this.arraySpinner2 = new String[]{
"Male", "Female"
};
Spinner s1 = (Spinner) findViewById(R.id.spinner2);
ArrayAdapter<String> adapter1 = new ArrayAdapter<>
(this,
android.R.layout.simple_spinner_dropdown_item, arraySpinner2
);
s1.setAdapter(adapter1);
editText1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
a = Integer.valueOf(editText1.getText().toString());
bundle.putInt("one",a);
}
});
editText2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
b = Integer.valueOf(editText2.getText().toString());
bundle.putInt("two",b);
}
});
EnterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent z = new Intent(activitysecond.this, activitythird.class);
startActivity(z);
z.putExtras(bundle);
}
});
}
}
The next activity to which i want to pass the values is
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class activitythird extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.thirdactivity);
}
public void thirdbutton(View view){
final TextView thirdtext=(TextView) findViewById(R.id.thirdtext);
Bundle seconddata=getIntent().getExtras();
int vala=seconddata.getInt("one");
int valb=seconddata.getInt("two");
thirdtext.setText(vala + " " +valb);
}
}
The values a and b are not passed and the thirdtext does not change
Please help!!
You start your activity before you add the bundle to your intent.
Try it like this:
Intent z = new Intent(activitysecond.this, activitythird.class);
z.putExtras(bundle);
startActivity(z);
Replace this
EnterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent z = new Intent(activitysecond.this, activitythird.class);
startActivity(z);
z.putExtras(bundle);
}
});
with
EnterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent z = new Intent(activitysecond.this, activitythird.class);
z.putExtras("one", Integer.parseInt(editText1.getText().toString()));
z.putExtras("two", Integer.parseInt(editText2.getText().toString()));
startActivity(z);
}
});
Remove ClickListener for the edit texts and add the following lines in onClick of EnterButton
a = Integer.valueOf(editText1.getText().toString());
bundle.putInt("one",a);
b = Integer.valueOf(editText2.getText().toString());
bundle.putInt("two",b);
At the below; putExtra comes before startActivity, that is the mistake.
EnterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent z = new Intent(activitysecond.this, activitythird.class);
startActivity(z);
z.putExtras(bundle);
}
});
try at below code;
EnterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent z = new Intent(activitysecond.this, activitythird.class);
z.putExtras(bundle); // first
startActivity(z); //second
}
});
Also editText onClickListeners should not be implemented for your case. You should get the variables via:
if (editText1.getText() != null) { // to avoid exception
a = Integer.valueOf(editText1.getText().toString());
bundle.putInt("one",a);
}
if (editText2.getText() != null) { to avoid exception
b = Integer.valueOf(editText2.getText().toString());
bundle.putInt("two",b);
}
Modify your code like this:
EnterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent z = new Intent(activitysecond.this, activitythird.class);
z.putExtras(bundle);
startActivity(z);
}
});
z.putExtras(bundle); must be higher that startActivity(z);

Categories

Resources