I have no clue how to fix this, please help!
I am creating a counter app that shows numbers every time user press a button. It starts from 0 and to a maximum of 9999. My problem is that after the user closes the app it again starts from 0 but what I want is display the last number the user pressed instead of 0 when user open app again. I tried many shared preference codes but none of them worked. Here is my code:
import android.content.Context;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private int x;
Context context = this;
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView number=(TextView) findViewById(R.id.numbers);
ImageButton btn_count=(ImageButton) findViewById(R.id.btn_countn);
ImageButton btn_reset=(ImageButton) findViewById(R.id.btn_resetn);
mp = MediaPlayer.create(context, R.raw.button_press);
number.setText(String.format("%04d", x)+"");
btn_count.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (mp.isPlaying()) {
mp.stop();
mp.release();
mp = MediaPlayer.create(context, R.raw.button_press);
} mp.start();
} catch(Exception e) { e.printStackTrace(); }
x = x +1;
number.setText(String.format("%04d", x)+"");
}
});
btn_reset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (mp.isPlaying()) {
mp.stop();
mp.release();
mp = MediaPlayer.create(context, R.raw.button_press);
} mp.start();
} catch(Exception e) { e.printStackTrace(); }
x=0;
number.setText(String.format("%04d", x)+"");
}
});
}
}
You will need to use the Android Preferences for this:
How?
define when the app is getting closed and then call a method where you can write the actual value of the counter
Example
SharedPreferences buttonCounterValue = getSharedPreferences("counter", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = buttonCounterValue.edit();
editor.putInt("myCounter", i); //
editor.commit();
and when the app is open again you will need to call another method and read it back...
Example:
SharedPreferences buttonCounterValue = getPreferences(Activity.MODE_PRIVATE);
int storedCounter = buttonCounterValue.getInt("myCounter", 0);
so validate what you store and check if the preference you get is 0, that means nothing was stored before, so you can beging the game from 0...
Using SharedPreferences you can do something like this:
public class MainActivity extends AppCompatActivity {
private int x;
SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
x = prefs.getInt("count", 0);
final TextView number=(TextView) findViewById(R.id.numbers);
ImageButton btn_count=(ImageButton) findViewById(R.id.btn_countn);
ImageButton btn_reset=(ImageButton) findViewById(R.id.btn_resetn);
number.setText(String.valueOf(x));
btn_count.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
x++;
prefs.edit().putInt("count", x).apply();
number.setText(String.valueOf(x));
}
});
btn_reset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
x=0;
prefs.edit().putInt("count", x).apply();
number.setText(String.valueOf(x));
}
});
}
}
Related
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();
}
}
});
I tried a lot with my code below . there is no compile error at all. when I used to start the MP3 which I added , in the logcat window it shows "start called in state 0". please help me with this code . Thanks in advance .I also want to know when we pause the audio , i need to get the song resume from there when i click the start button (or) Is there any resume function for it , Let me know in the comments section . Thanks in advance. Here's my Java code
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
private MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button mButton = (Button) findViewById(R.id.btnStart);
Button mButton1 = (Button) findViewById(R.id.btnStop);
Button mButton2 = (Button) findViewById(R.id.btnPause);
mp = new MediaPlayer();
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.start();
}
});
mButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.stop();
}
});
mButton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer.create(MainActivity.this, R.raw.ch);
mp.pause();
}
});
create a class named AudioClip
public class AudioClip {
public static boolean loop = false;
public static MediaPlayer mediaPlayer;
private static SoundPool soundPool;
public static boolean isplayingAudio = false;
public static void playAudio(Context c, int id) {
mediaPlayer = MediaPlayer.create(c, id);
soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);
if (!mediaPlayer.isPlaying()) {
isplayingAudio = true;
mediaPlayer.start();
mediaPlayer.setLooping(loop);
}
}
public static void stopAudio() {
isplayingAudio = false;
mediaPlayer.stop();
}
}
on other activity to play music
Context m = CuteActivity.this;
AudioClip.playAudio(m, R.raw.ch);\
and to stop
if (AudioClip.isplayingAudio) {
AudioClip.stopAudio();
}
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);
I am a newbie in android app development. For now my challenge is to add two buttons in my UI one for playing an mp3 file and the other for stopping it. I am able to do the first successfully and as I try to do the stop one, I see no result. My code is as following:
package ir.polyglotcenter.childrenmostfrequentwords;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Main extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button myButtonOne = (Button) findViewById(R.id.btn_audio);
myButtonOne.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer media = MediaPlayer.create(Main.this, R.raw.audio);
media.start();
}
});
//this is to stop the audio flow
Button myButtonTwo = (Button) findViewById(R.id.btn_stop);
myButtonTwo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer media = MediaPlayer.create(Main.this, R.raw.audio);
media.stop();
}
});
}
}
Try this code:
public class Main extends Activity {
protected MediaPlayer mMediaPlayer;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mMediaPlayer = MediaPlayer.create(Main.this, R.raw.audio);
Button myButtonOne = (Button) findViewById(R.id.btn_audio);
myButtonOne.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mMediaPlayer.prepare();
mMediaPlayer.start();
}
});
//this is to stop the audio flow
Button myButtonTwo = (Button) findViewById(R.id.btn_stop);
myButtonTwo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(mMediaPlayer.isPlaying())
mMediaPlayer.stop();
}
});
}
}
Play and Stop all song for all rows.
The Point is implement MediaPlayer in the loop of if or any loop you have:
if(playandstop==true){
mp=MediaPlayer.create(MainActivity.this, resourceIIIDD);
mp.start();
playandstop=false;
}else{
mp.stop();
playandstop=true;
}
Ive got this button code as shown below but it only have one button and one textview my project require meant is that there needs to be two or more buttons that will count into separate systems but use the same code. Ill include the main code below but any help adding more functionality into the system is much loved!
main code
package com.example.counter;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
// Private member field to keep track of the count
private static int mCount = 0;
private TextView countTextView;
private Button countButton;
public static final String PREFS_NAME = "com.example.myApp.mCount";
private SharedPreferences settings = null;
private SharedPreferences.Editor editor = null;
/** ADD THIS METHOD **/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
countTextView = (TextView) findViewById(R.id.TextViewCount);
countButton = (Button) findViewById(R.id.ButtonCount);
countButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mCount++;
countTextView.setText("Count: " + mCount);
editor = settings.edit();
editor.putInt("mCount", mCount);
editor.commit();
}
});
settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onResume() {
super.onResume();
mCount = settings.getInt("mCount", 0);
countTextView.setText("Count: " + mCount);
}
}
Create 3 buttons in your xml, lets assume their ids are ButtonCount, ButtonCount2 and ButtonCount3 as well as the countButton2 and countButton3 being declared as well. Then initialize them as follows:
countButton = (Button) findViewById(R.id.ButtonCount);
countButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mCount++;
countTextView.setText("Count: " + mCount);
editor = settings.edit();
editor.putInt("mCount", mCount);
editor.commit();
}
});
countButton2 = (Button) findViewById(R.id.ButtonCount2);
countButton2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//do something here
}
});
countButton3 = (Button) findViewById(R.id.ButtonCount3);
countButton3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//do something else here
}
});