I am creating a simple Click Counter Android App using Java. I am new to Java. Here is my code below, the gui has different buttons with different functions, for example the count button itself, a reset count button, and a mute sound button.
public class wazeefa extends Activity {
//Count Button
TextView txtCount;
ImageView image;
Button btnCount;
Button wmute;
Button wreset;
public static int count=0;
SharedPreferences app_preferences;
MediaPlayer mpButtonClick;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// The activity is being created.
setContentView(R.layout.wazeefa);
//SAVE COUNT
app_preferences = this.getSharedPreferences("myPrefscount", MODE_WORLD_READABLE);
count = app_preferences.getInt("count", 0);
txtCount = (TextView)findViewById(R.id.wcount);
txtCount.setText("This app has been started " + count + " times.");
txtCount = (TextView)findViewById(R.id.wcount);
txtCount.setText("This app has been started " + count + " times.");
//Button SOUND AND COUNT
mpButtonClick = MediaPlayer.create(this, R.raw.bubble);
//RESET Button
wreset = (Button)findViewById(R.id.wreset);
txtCount = (TextView)findViewById(R.id.wcount);
txtCount.setText(String.valueOf(count));
btnCount = (Button)findViewById(R.id.wclick);
btnCount.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
image = (ImageView) findViewById(R.id.imageview);
count++;
if (count > 50) count = 0; image.setImageResource(R.drawable.duroodimage);
if (count > 0) image.setImageResource(R.drawable.duroodimage);
if (count > 9) image.setImageResource(R.drawable.zikrimage);
if (count > 39) image.setImageResource(R.drawable.duroodimage);
txtCount.setText(String.valueOf(count));
}
});
wreset.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
count = 0;
image.setImageResource(R.drawable.duroodimage);;
txtCount.setText("0");
}
});
}
#Override
protected void onPause() {
super.onPause();
// save count value here
SharedPreferences.Editor editor = app_preferences.edit();
editor.putInt("count", count);
editor.commit();
}
//MUTE button
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.wmute:
AudioManager.setMode(AudioManager.MODE_IN_CALL);
AudioManager.setStreamSolo(AudioManager.STREAM_VOICE_CALL, true);
default:
AudioManager.setMode(AudioManager.MODE_NORMAL );
AudioManager.setStreamSolo(AudioManager.STREAM_VOICE_CALL, false);
break;
}
}
I have 1 issue:
When I go back into the app and the count shows as '5' just for example, the Reset button no longer functions - it does nothing, I get an error message on AVD saying 'unfortunately 'App' has stopped'. But when I continue the count and then hit the Reset button it works changes the count to zero again
Any suggestions on the above issue, have I missed anything or placed code in the wrong areas? The button sound was working before I edited the code, to save the 'count' data.
Let me know if I'm being vague...
The Crash Log:
12-24 18:07:42.661: W/Trace(3633): Unexpected value from nativeGetEnabledTags: 0
12-24 18:07:42.741: D/AndroidRuntime(3633): Shutting down VM
12-24 18:07:42.741: W/dalvikvm(3633): threadid=1: thread exiting with uncaught exception (group=0x40a70930)
12-24 18:07:42.811: E/AndroidRuntime(3633): FATAL EXCEPTION: main
12-24 18:07:42.811: E/AndroidRuntime(3633): java.lang.NullPointerException
12-24 18:07:42.811: E/AndroidRuntime(3633): at com.shaadcorp.wazaifapp.wazeefa$2.onClick(wazeefa.java:81)
12-24 18:07:42.811: E/AndroidRuntime(3633): at android.view.View.performClick(View.java:4202)
12-24 18:07:42.811: E/AndroidRuntime(3633): at android.view.View$PerformClick.run(View.java:17340)
12-24 18:07:42.811: E/AndroidRuntime(3633): at android.os.Handler.handleCallback(Handler.java:725)
12-24 18:07:42.811: E/AndroidRuntime(3633): at android.os.Handler.dispatchMessage(Handler.java:92)
12-24 18:07:42.811: E/AndroidRuntime(3633): at android.os.Looper.loop(Looper.java:137)
12-24 18:07:42.811: E/AndroidRuntime(3633): at android.app.ActivityThread.main(ActivityThread.java:5039)
12-24 18:07:42.811: E/AndroidRuntime(3633): at java.lang.reflect.Method.invokeNative(Native Method)
12-24 18:07:42.811: E/AndroidRuntime(3633): at java.lang.reflect.Method.invoke(Method.java:511)
12-24 18:07:42.811: E/AndroidRuntime(3633): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
12-24 18:07:42.811: E/AndroidRuntime(3633): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
12-24 18:07:42.811: E/AndroidRuntime(3633): at dalvik.system.NativeStart.main(Native Method)
12-24 18:07:48.842: I/Process(3633): Sending signal. PID: 3633 SIG: 9
12-24 18:07:51.572: E/Trace(3808): error opening trace file: No such file or directory (2)
I guess I didn't see mpButtonClick.start() anywhere in your code. That's why sound is not playing. Add mpButtonClick.start(). to your ClickListener.
fixed issue, thanks for your help Passionate Androiden.
public class wazeefa extends Activity {
//Count Button
TextView txtCount;
ImageView image;
Button btnCount;
Button wmute;
Button wreset;
public static int count=0;
SharedPreferences app_preferences;
MediaPlayer mpButtonClick;
AudioManager audioManager;
public static boolean mutestatus=false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// The activity is being created.
setContentView(R.layout.wazeefa);
audioManager =
(AudioManager)getSystemService(Context.AUDIO_SERVICE);
//SAVE COUNT
app_preferences = this.getSharedPreferences("myPrefscount", MODE_WORLD_READABLE);
count = app_preferences.getInt("count", 0);
txtCount = (TextView)findViewById(R.id.wcount);
txtCount.setText("This app has been started " + count + " times.");
image = (ImageView) findViewById(R.id.imageview);
txtCount = (TextView)findViewById(R.id.wcount);
txtCount.setText("This app has been started " + count + " times.");
//Button SOUND AND COUNT
mpButtonClick = MediaPlayer.create(this, R.raw.bubble);
//RESET Button
wreset = (Button)findViewById(R.id.wreset);
txtCount = (TextView)findViewById(R.id.wcount);
txtCount.setText(String.valueOf(count));
btnCount = (Button)findViewById(R.id.wclick);
wmute=(Button)findViewById(R.id.wmute);
btnCount.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
count++;
if (count > 50) count = 0; image.setImageResource(R.drawable.duroodimage);
if (count > 0) image.setImageResource(R.drawable.duroodimage);
if (count > 9) image.setImageResource(R.drawable.zikrimage);
if (count > 39) image.setImageResource(R.drawable.duroodimage);
txtCount.setText(String.valueOf(count));
mpButtonClick.start();
}
});
wreset.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
count = 0;
image.setImageResource(R.drawable.duroodimage);;
txtCount.setText("0");
SharedPreferences.Editor editor = app_preferences.edit();
editor.putInt("count", count);
editor.commit();
}
});
wmute.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(!mutestatus){
mutestatus=true;
audioManager.setMode(AudioManager.MODE_IN_CALL);
audioManager.setStreamSolo(AudioManager.STREAM_VOICE_CALL, true);
Log.v("'test....",""+mutestatus);
}
else{
mutestatus=false;
audioManager.setMode(AudioManager.MODE_NORMAL );
audioManager.setStreamSolo(AudioManager.STREAM_VOICE_CALL, false);
Log.v("'test....",""+mutestatus);
}
}});
}
#Override
protected void onPause() {
super.onPause();
// save count value here
SharedPreferences.Editor editor = app_preferences.edit();
editor.putInt("count", count);
editor.commit();
}
}
Related
Everybody,
I'm trying to record audio.
The audio is record perfectly when record button is clicked.
I try to stop the record and the app crashing immediately after the stop button is clicked.
Can you please help me on fixing this code so i could continue building my project.
Here's part of the code:
public class window2 extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
Spinner spinner;//choice between record and Speech-2-text.
Button play,stop,record;//record, stop and replay buttons.
String outputFile;//the record file.
MediaRecorder myAudioRecorder;//the record method.
int reRecord = 0;//reRecord value.
int pathVal = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_window2);
spinner = findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(this);//upon change between record and S2T.
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor edit = sharedPreferences.edit();
if( sharedPreferences.getInt("pathVal",0) == 0)
edit.putInt("pathVal",1);
else {
pathVal = sharedPreferences.getInt("pathVal", pathVal);
edit.putInt("pathVal",pathVal+1);
}
pathVal = sharedPreferences.getInt("pathVal", 0);
edit.commit();
//3 buttons for record,stop and replay.
play = findViewById(R.id.button14);
stop = findViewById(R.id.button13);
record = findViewById(R.id.button11);
//to immune issues that may start if the buttons are enabled.
stop.setEnabled(false);
play.setEnabled(false);
//the file of recording.
outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/"+pathVal+".3gp";
//record settings.
myAudioRecorder = new MediaRecorder();
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
myAudioRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
myAudioRecorder.setOutputFile(outputFile);
//record button click.
record.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
play.setEnabled(false);
try{
//if we want to re record.
if(reRecord == 1)
{
//we build the settings again.
myAudioRecorder = new MediaRecorder();
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
myAudioRecorder.setOutputFile(outputFile);
}
//prepare and start methods.
myAudioRecorder.prepare();
myAudioRecorder.start();
}catch (IllegalStateException ise) {
//something
}catch (IOException ioe){
//something
}
record.setEnabled(false);
stop.setEnabled(true);
Toast.makeText(window2.this, "Recording...", Toast.LENGTH_SHORT).show();
}
});
//stop button click.
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
myAudioRecorder.stop();
myAudioRecorder.reset();
reRecord = 1;
myAudioRecorder = null;
record.setEnabled(true);
stop.setEnabled(false);
play.setEnabled(true);
Toast.makeText(window2.this, "Recorded!", Toast.LENGTH_SHORT).show();
}
});
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MediaPlayer mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(outputFile);
mediaPlayer.prepare();
mediaPlayer.start();
Toast.makeText(window2.this, "Playing.", Toast.LENGTH_SHORT).show();
} catch (Exception e){
//something
}
}
});
}
public void OpenWindow4(View view)
{
Spinner spinner = findViewById(R.id.spinner3);
String SpinTxt = spinner.getSelectedItem().toString();
EditText edit2 = findViewById(R.id.editText);
String editTextTxt = edit2.getText().toString();
Intent intent = new Intent(this,window4.class);
intent.putExtra("THE_TEXT",editTextTxt);
intent.putExtra("SPIN_CHOICE",SpinTxt);
startActivity(intent);
}
public void OpenWindow4Speech(View view)
{
Spinner spinner = findViewById(R.id.spinner4);
String SpinTxt = spinner.getSelectedItem().toString();
EditText edit2 = findViewById(R.id.editText2);
String editTextTxt = edit2.getText().toString();
Intent intent = new Intent(this,window4.class);
intent.putExtra("THE_RECORD",outputFile);
intent.putExtra("SPIN_CHOICE",SpinTxt);
intent.putExtra("THE_TEXT",editTextTxt);
startActivity(intent);
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String item = adapterView.getItemAtPosition(i).toString();
if (item.equals("S2T"))
{
Intent intent = new Intent(this,windows2B.class);
startActivity(intent);
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
and here is the logcat:
01-13 08:42:27.105 1031-1031/com.example.simplenigal.prealphabuilt V/MediaRecorder: prepare
01-13 08:42:27.105 1031-1031/com.example.simplenigal.prealphabuilt V/MediaRecorder: start
01-13 08:42:27.105 1031-1031/com.example.simplenigal.prealphabuilt E/MediaRecorder: start failed: -38
01-13 08:42:27.757 1031-1038/com.example.simplenigal.prealphabuilt I/art: Do partial code cache collection, code=115KB, data=106KB
01-13 08:42:27.757 1031-1038/com.example.simplenigal.prealphabuilt I/art: After code cache collection, code=115KB, data=106KB
01-13 08:42:27.757 1031-1038/com.example.simplenigal.prealphabuilt I/art: Increasing code cache capacity to 512KB
01-13 08:42:27.759 1031-1038/com.example.simplenigal.prealphabuilt I/art: Compiler allocated 6MB to compile void android.view.ViewRootImpl.performTraversals()
01-13 08:42:31.382 1031-1031/com.example.simplenigal.prealphabuilt I/ViewRootImpl: ViewRoot's Touch Event : ACTION_DOWN
01-13 08:42:31.452 1031-1031/com.example.simplenigal.prealphabuilt I/ViewRootImpl: ViewRoot's Touch Event : ACTION_UP
01-13 08:42:31.462 1031-1031/com.example.simplenigal.prealphabuilt V/MediaRecorder: stop
01-13 08:42:31.462 1031-1031/com.example.simplenigal.prealphabuilt E/MediaRecorder: stop called in an invalid state: 0
01-13 08:42:31.463 1031-1031/com.example.simplenigal.prealphabuilt D/AndroidRuntime: Shutting down VM
01-13 08:42:31.468 1031-1031/com.example.simplenigal.prealphabuilt E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.simplenigal.prealphabuilt, PID: 1031
java.lang.IllegalStateException
at android.media.MediaRecorder.native_stop(Native Method)
at android.media.MediaRecorder.stop(MediaRecorder.java:896)
at com.example.simplenigal.prealphabuilt.window2$2.onClick(window2.java:102)
at android.view.View.performClick(View.java:5624)
at android.view.View$PerformClick.run(View.java:22441)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6316)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
thanks to every one who paying attention and helping.
Still looking for help
I was using an integer for the money factor in this little test app but I realized that long was more appropriate and I changed the code so that money is a long instead of an int and I changed SharedPreferences appropriately as well, however it does not work wheras it did when I used int. Thank you for the help!
public class Home extends AppCompatActivity {
SharedPreferences pref;
SharedPreferences.Editor editor;
Intent intent;
TextView home_money_view;
long money; // this is the variable that is causing problems
int initial;
final long TEST = (long)-1;
int gold_pieces;
int gold_price = 50;
TimerTask timerTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
home_money_view = (TextView) findViewById(R.id.home_money_view)
pref = getApplicationContext().getSharedPreferences("MY_PREFS", MODE_PRIVATE);
editor = pref.edit();
money = pref.getLong("temp_money",Long.MIN_VALUE); // get value
if (money==Long.MIN_VALUE){
money=0;
}
gold_pieces = pref.getInt("temp_gold",-1);
if (gold_pieces==-1){
gold_pieces=0;
}
initial = pref.getInt("initial",0);
money+=initial;
editor.putInt("initial",0);
editor.commit();
home_money_view = (TextView) findViewById(R.id.home_money_view);
home_money_view.setText(money+"");
editor.commit();
}
public void backToSplash(View view){
intent = new Intent(Home.this,BusinessSelector.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
public void goToSecondView(View view){
long temp_money = money;
editor.putLong("temp_money",temp_money); // set value
int temp_gold = gold_pieces;
editor.putInt("temp_gold",temp_gold);
editor.commit();
intent = new Intent(Home.this,SecondView.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
public void goToOtherView(View view) {
long temp_money = money;
editor.putLong("temp_money",temp_money); // set value
int temp_gold = gold_pieces;
editor.putInt("temp_gold", temp_gold);
editor.commit();
intent = new Intent(Home.this, Next.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
Logcat:
04-13 19:01:03.675 12896-12896/com.exampleryancocuzzo.ryan.markettycoon E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.exampleryancocuzzo.ryan.markettycoon/com.exampleryancocuzzo.ryan.markettycoon.Home}: java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long
at android.app.SharedPreferencesImpl.getLong(SharedPreferencesImpl.java:228)
at com.exampleryancocuzzo.ryan.markettycoon.Home.onCreate(Home.java:56)
at android.app.Activity.performCreate(Activity.java:4466)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
I created an android app that tests your reflects speed.
at first the app is still
when you press(State 0) the app starts a thread that waits a couple of seconds before showing a green screen.
When the green screen is shown(State 1) you have to press as fast as you can.
if you press the green(state 2) you are shown the reflect time
the problem I'm having that when a person clicks too soon, i have to stop the thread which causes the app to crash(thread.stop()).
Any suggestions?
public class MainActivity extends Activity implements OnClickListener{
TextView tvs,tvas;
RelativeLayout rl;
int state; //0=red 1=green 2=tapped-green
long end,start,result;
Thread th;
Boolean dont;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rl = (RelativeLayout) findViewById(R.id.rl);
tvs = (TextView) findViewById(R.id.tvs);
tvas = (TextView) findViewById(R.id.tvas);
dont=true;
state=0;
Typeface myTypeface = Typeface.createFromAsset(this.getAssets(),"RobotoCondensed-Bold.ttf");
tvs.setTypeface(myTypeface);
tvas.setTypeface(myTypeface);
rl.setOnClickListener(this);
tvs.setOnClickListener(this);
tvas.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (state) {
case 0:
tvs.setText("Any Min Now");
rl.setBackgroundColor(Color.rgb(255, 68, 68));
final Handler mHandler = new Handler();
state=1;
dont=true;
th = new Thread((new Runnable() {public void run() {while (true){try {Thread.sleep(randInt());mHandler.post(new Runnable() {public void run() {
if(dont){ //not helping
rl.setBackgroundColor(Color.GREEN);
start = SystemClock.uptimeMillis();
state=2;
}
}});} catch (Exception e) {}}}}));
th.start();
break;
case 1:
tvs.setText("Too Soon!");
tvas.setText("Tap AnyWhere To restart");
dont=false;
rl.setBackgroundColor(Color.rgb(255, 68, 68));
state=0;
break;
case 2:
end = SystemClock.uptimeMillis();
result=end-start;
tvs.setText("UR Reaction Time= "+result+"ms");
tvas.setText("Tap AnyWhere To restart");
state=0;
dont=false;
th.interrupt(); //giving me wrong numbers
break;
}
}
public static int randInt() { //creates a random number
Random rand = new Random();
int randomNum = rand.nextInt((6000 - 2000) + 1) + 2000;
return randomNum;
}
}
LogCat:
03-07 22:16:05.575: I/WindowState(840): WIN DEATH: Window{45b08280 u0 com.afm.reflects/com.afm.reflects.MainActivity}
03-07 22:16:05.575: I/ActivityManager(840): Process com.afm.reflects (pid 32055) (adj 11) has died.
03-07 22:16:52.391: V/SmartFaceService - 3rd party pause(840): onReceive
[android.intent.action.ACTIVITY_STATE/com.afm.reflects/create]
03-07 22:17:03.471: E/AndroidRuntime(864): Process: com.afm.reflects, PID: 864
03-07 22:17:03.471: E/AndroidRuntime(864): at com.afm.reflects.MainActivity.onClick(MainActivity.java:73)
03-07 22:17:03.482: W/ActivityManager(840): Force finishing activity com.afm.reflects/.MainActivity
03-07 22:17:03.522: V/SmartFaceService - 3rd party pause(840): onReceive
[android.intent.action.ACTIVITY_STATE/com.afm.reflects/pause]
03-07 22:17:03.562: D/CrashAnrDetector(840): processName: com.afm.reflects
03-07 22:17:03.562: D/CrashAnrDetector(840): broadcastEvent : com.afm.reflects data_app_crash
03-07 22:17:05.634: I/ActivityManager(840): Process com.afm.reflects (pid 864) (adj 9) has died.
03-07 22:17:05.644: I/WindowState(840): WIN DEATH: Window{45514be0 u0 com.afm.reflects/com.afm.reflects.MainActivity}
03-07 22:18:53.869: V/SmartFaceService - 3rd party pause(840): onReceive
[android.intent.action.ACTIVITY_STATE/com.afm.reflects/create]
03-07 22:19:11.867: E/AndroidRuntime(1649): Process: com.afm.reflects, PID: 1649
03-07 22:19:11.867: E/AndroidRuntime(1649): at com.afm.reflects.MainActivity.onClick(MainActivity.java:73)
03-07 22:19:11.877: W/ActivityManager(840): Force finishing activity com.afm.reflects/.MainActivity
03-07 22:19:11.917: D/CrashAnrDetector(840): processName: com.afm.reflects
03-07 22:19:11.917: V/SmartFaceService - 3rd party pause(840): onReceive
[android.intent.action.ACTIVITY_STATE/com.afm.reflects/pause]
03-07 22:19:11.927: D/CrashAnrDetector(840): broadcastEvent : com.afm.reflects data_app_crash
Thanks to the replies on NFC and a few certain things, I've understood and managed to compile a code in which the users will be able to read a tag, and if the tag contains a string that is similar to my code, a coupon will be added (image changes) and an integer goes up by 1. This integer will be saved by SharedPreferences and it is used to determine how many coupons the users have collected and show it onResume.
However, after compiling, when I try to run it, my application stops immediately. Can someone help me check on what I may have go wrong? I know it's kinda long but I really have no idea what went wrong.
#TargetApi(10)
//I have to use this line of code because I'm targetted to code at API 8 but some NFC functionalities that I use requires API 10.
public class CouponManager extends Activity {
private static final String TAG = "NFCReadTag";
private NfcAdapter mNfcAdapter;
private IntentFilter[] mNdefExchangeFilters;
private PendingIntent mNfcPendingIntent;
public static final String PREF_FILE_NAME = "PrefFile";
private int[] images = new int[10];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.coupon_layout);
//List of images
images[0]=R.drawable.cp0;
images[1]=R.drawable.cp1;
images[2]=R.drawable.cp2;
images[3]=R.drawable.cp3;
images[4]=R.drawable.cp4;
images[5]=R.drawable.cp5;
images[6]=R.drawable.cp6;
images[7]=R.drawable.cp7;
images[8]=R.drawable.cp8;
images[9]=R.drawable.cp9;
images[10]=R.drawable.cp10;
//Restore preferences
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
int storedPreference = preferences.getInt("storedInt", 0);
//Image to use depending on coupon collected
final ImageView img = new ImageView(this);
if(storedPreference!=10)
{
img.setImageResource(images[storedPreference]);
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setTitle("Redeem Your Coupon?");
builder.setInverseBackgroundForced(true);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", 0); // value to store
editor.commit();
img.setImageResource(images[0]);
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
img.setImageResource(images[10]);
}
});
}
//Check and send Intent from NFC tag discovered
mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
mNfcPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
| Intent.FLAG_ACTIVITY_CLEAR_TOP), 0);
IntentFilter coupontag = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
coupontag.addDataScheme("http");
coupontag.addDataAuthority("www.ichatime.com", null);
coupontag.addDataPath(".*", PatternMatcher.PATTERN_SIMPLE_GLOB);
mNdefExchangeFilters = new IntentFilter[] { coupontag };
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected void onResume() {
super.onResume();
if(mNfcAdapter != null) {
mNfcAdapter.enableForegroundDispatch(this, mNfcPendingIntent,
mNdefExchangeFilters, null);
} else {
Toast.makeText(getApplicationContext(), "Sorry, No NFC Adapter found.", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onPause() {
super.onPause();
if(mNfcAdapter != null) mNfcAdapter.disableForegroundDispatch(this);
}
#Override
protected void onStop() {
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
int storedPreference = preferences.getInt("storedInt", 0);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
int storedPreference = preferences.getInt("storedInt", 0);
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
NdefMessage[] messages = null;
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
if (rawMsgs != null) {
messages = new NdefMessage[rawMsgs.length];
for (int i = 0; i < rawMsgs.length; i++) {
messages[i] = (NdefMessage) rawMsgs[i];
}
}
if(messages[0] != null) {
String result="";
byte[] payload = messages[0].getRecords()[0].getPayload();
// this assumes that we get back am SOH followed by host/code
for (int b = 1; b<payload.length; b++) { // skip SOH
result += (char) payload[b];
}
if (result == "ichatime.com")
{
final ImageView img = new ImageView(this);
Toast.makeText(getApplicationContext(), "Coupon collected!", Toast.LENGTH_SHORT).show();
if (storedPreference!=10)
{
storedPreference++;
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference);
img.setImageResource(images[storedPreference]);
}
if (storedPreference==10)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setTitle("Redeem Your Coupon?");
builder.setInverseBackgroundForced(true);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", 0); // value to store
editor.commit();
img.setImageResource(images[0]);
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
img.setImageResource(images[10]);
}
});
}
else
{
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", 10);
img.setImageResource(images[10]);
}}
else
{
Toast.makeText(getApplicationContext(), "Wrong tag detected!", Toast.LENGTH_SHORT).show();
}
//Debugging Mode to see what is contained in the tags.
// Toast.makeText(getApplicationContext(), "Tag Contains " + result, Toast.LENGTH_SHORT).show();
}
}
}
}
Logcat errors:
>11-26 01:16:11.869: D/AndroidRuntime(550): Shutting down VM
>
11-26 01:16:11.869: W/dalvikvm(550): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
>
11-26 01:16:11.929: I/dalvikvm(550): threadid=3: reacting to signal 3
>
11-26 01:16:11.979: E/AndroidRuntime(550): FATAL EXCEPTION: main
>
**11-26 01:16:11.979: E/AndroidRuntime(550): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ponpon/com.example.ponpon.MainActivity}: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ponpon/com.example.ponpon.CouponManager}: java.lang.ArrayIndexOutOfBoundsException: length=10; index=10**
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.app.ActivityThread.access$600(ActivityThread.java:123)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.os.Handler.dispatchMessage(Handler.java:99)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.os.Looper.loop(Looper.java:137)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.app.ActivityThread.main(ActivityThread.java:4424)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at java.lang.reflect.Method.invokeNative(Native Method)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at java.lang.reflect.Method.invoke(Method.java:511)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at dalvik.system.NativeStart.main(Native Method)
>
11-26 01:16:11.979: E/AndroidRuntime(550): Caused by: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ponpon/com.example.ponpon.CouponManager}: java.lang.ArrayIndexOutOfBoundsException: length=10; index=10
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.app.ActivityThread.startActivityNow(ActivityThread.java:1797)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:135)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:347)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:682)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.widget.TabHost.setCurrentTab(TabHost.java:346)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.widget.TabHost.addTab(TabHost.java:236)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at com.example.ponpon.MainActivity.onCreate(MainActivity.java:37)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.app.Activity.performCreate(Activity.java:4465)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
>
11-26 01:16:11.979: E/AndroidRuntime(550): ... 11 more
>
11-26 01:16:11.979: E/AndroidRuntime(550): Caused by: java.lang.ArrayIndexOutOfBoundsException: length=10; index=10
>
11-26 01:16:11.979: E/AndroidRuntime(550): at com.example.ponpon.CouponManager.onCreate(CouponManager.java:53)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.app.Activity.performCreate(Activity.java:4465)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
>
11-26 01:16:11.979: E/AndroidRuntime(550): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
>
11-26 01:16:11.979: E/AndroidRuntime(550): ... 21 more
What did I do wrong with my arrays? Thanks for the clarification guys!
Your logcat is printing an ArrayOutOfBounds exception on your onCreate method.
The problem is that you are declaring a 10 items sized array, and then trying to put 11 items on it.
You have to declare a new int[11] array.
I seem to have solved the problem by adding the array count by 1. What I don't understand is, I want to keep 11 items in the array so isn't
private int[] images = new int[10] enough?
Cause from what I understand, int[0] keeps the first value, hence int[10] will keep the eleventh value? Thank you guys!
When i start my app and press stop or pause the android app will crash. It works fine if you press play first and then stop or pause. I searched on google and stackoverflow but i couldn't find much about it. I think the problem is because of a NullPointerException but since i'm new too java it doesn't tell me much about the problem
The code:
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class myMain extends Activity implements
MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener,
MediaPlayer.OnErrorListener, MediaPlayer.OnBufferingUpdateListener, OnClickListener {
private String TAG = getClass().getSimpleName();
private MediaPlayer mp= null;
private Button play;
private Button pause;
private Button stop;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
play = (Button) findViewById(R.id.play);
pause = (Button) findViewById(R.id.pause);
stop = (Button) findViewById(R.id.stop);
play.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
play();
}
});
pause.setOnClickListener(new View.OnClickListener() {
public void onClick(View view){
pause();
}
});
stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View view){
stop();
}
});
}
private void play() {
Uri myUri = Uri.parse("url");
try {
if (mp == null) {
this.mp = new MediaPlayer();
} else {
mp.stop();
mp.reset();
}
mp.setDataSource(this, myUri); // Go to Initialized state
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setOnPreparedListener(this);
mp.setOnBufferingUpdateListener(this);
mp.setOnErrorListener(this);
mp.prepareAsync();
Log.d(TAG, "LoadClip Done");
} catch (Throwable t) {
Log.d(TAG, t.toString());
}
}
public void onPrepared(MediaPlayer mp) {
Log.d(TAG, "Stream is prepared");
mp.start();
}
private void pause() {
mp.pause();
}
private void stop() {
mp.stop();
}
#Override
public void onDestroy() {
super.onDestroy();
stop();
}
public void onCompletion(MediaPlayer mp) {
stop();
}
public boolean onError(MediaPlayer mp, int what, int extra) {
StringBuilder sb = new StringBuilder();
sb.append("Media Player Error: ");
switch (what) {
case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
sb.append("Not Valid for Progressive Playback");
break;
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
sb.append("Server Died");
break;
case MediaPlayer.MEDIA_ERROR_UNKNOWN:
sb.append("Unknown");
break;
default:
sb.append(" Non standard (");
sb.append(what);
sb.append(")");
}
sb.append(" (" + what + ") ");
sb.append(extra);
Log.e(TAG, sb.toString());
return true;
}
public void onBufferingUpdate(MediaPlayer mp, int percent) {
Log.d(TAG, "PlayerService onBufferingUpdate : " + percent + "%");
}
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
The errors:
02-11 20:45:43.837: D/AndroidRuntime(338): Shutting down VM
02-11 20:45:43.837: W/dalvikvm(338): threadid=1: thread exiting with uncaught exception (group=0x40015560)
02-11 20:45:43.857: E/AndroidRuntime(338): FATAL EXCEPTION: main
02-11 20:45:43.857: E/AndroidRuntime(338): java.lang.NullPointerException
02-11 20:45:43.857: E/AndroidRuntime(338): at wadio.media.internetradio.myMain.stop(myMain.java:95)
02-11 20:45:43.857: E/AndroidRuntime(338): at wadio.media.internetradio.myMain.access$2(myMain.java:94)
02-11 20:45:43.857: E/AndroidRuntime(338): at wadio.media.internetradio.myMain$3.onClick(myMain.java:55)
02-11 20:45:43.857: E/AndroidRuntime(338): at android.view.View.performClick(View.java:2485)
02-11 20:45:43.857: E/AndroidRuntime(338): at android.view.View$PerformClick.run(View.java:9080)
02-11 20:45:43.857: E/AndroidRuntime(338): at android.os.Handler.handleCallback(Handler.java:587)
02-11 20:45:43.857: E/AndroidRuntime(338): at android.os.Handler.dispatchMessage(Handler.java:92)
02-11 20:45:43.857: E/AndroidRuntime(338): at android.os.Looper.loop(Looper.java:123)
02-11 20:45:43.857: E/AndroidRuntime(338): at android.app.ActivityThread.main(ActivityThread.java:3683)
02-11 20:45:43.857: E/AndroidRuntime(338): at java.lang.reflect.Method.invokeNative(Native Method)
02-11 20:45:43.857: E/AndroidRuntime(338): at java.lang.reflect.Method.invoke(Method.java:507)
02-11 20:45:43.857: E/AndroidRuntime(338): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
02-11 20:45:43.857: E/AndroidRuntime(338): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
02-11 20:45:43.857: E/AndroidRuntime(338): at dalvik.system.NativeStart.main(Native Method)
In your stop() method you access the mp variable. However, the mp variable is null until you press play (and the play() method is called). So when you try to access the null variable a NullPointerException is thrown.
A very simple way to stop the NullPointerException is to do something like this:
private void pause() {
if(mp!=null) mp.pause();
}
private void stop() {
if(mp!=null) mp.stop();
}
Of course this solution doesn't account for cases where pause or stop is called twice. Take a look at the MediaPlayer documentation for more info on state management.