How can I change the volume properly? - java

I have been stuck on this for way too long (4 hours yesterday, 3 hours today!) now. In my main menu screen, I have a mute button. I want it to call a method in my background service, which mutes all of the MediaPlayer audio that would be played in the background of my game.
Full code here
Here is something that might be causing the issue:
I am getting the error whenever the audio plays (which plays fine):
QCMediaPlayer mediaplayer NOT present
E/MediaPlayer﹕ Should have subtitle controller already set
package com.example.USERNAME.buttonsmasher;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
public class TwentySeconds extends Service {
static MediaPlayer ten;
static MediaPlayer three;
final String TAG = "MyCountdown";
static CountDownTimer cdt;
double millisUntilFinishedRounded;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Context context = this;
three = MediaPlayer.create(TwentySeconds.this, R.raw.threetwoone);
ten = MediaPlayer.create(TwentySeconds.this, R.raw.tenmoreseconds);
// ten = MediaPlayer.create(TwentySeconds.this, R.raw.tenmoreseconds);
// three = MediaPlayer.create(TwentySeconds.this, R.raw.threetwoone);
Log.v(TAG, "In start command");
cdt = new CountDownTimer(20000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
Log.v(TAG, millisUntilFinished + "left");
millisUntilFinishedRounded = (millisUntilFinished / 1000) * 1000;
if (millisUntilFinishedRounded == 10000) { //TEN SECONDS
// ten = MediaPlayer.create(TwentySeconds.this, R.raw.tenmoreseconds);
// while(ten == null){
ten = MediaPlayer.create(TwentySeconds.this, R.raw.tenmoreseconds);
// }
ten.start();
}
if (millisUntilFinishedRounded == 3000) {
/* Context context = this;
three = MediaPlayer.create(TwentySeconds.this, R.raw.threetwoone);
*/
// while(three == null){
three = MediaPlayer.create(TwentySeconds.this, R.raw.tenmoreseconds);
//}
three.start();
}
}
#Override
public void onFinish() {
Log.v(TAG, "Finished");
Intent intent = new Intent(TwentySeconds.this, GameOver.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Log.v(TAG, "About to start activity");
startActivity(intent);
}
};
cdt.start();
return START_STICKY;
}
public static void stopTimer() {
cdt.cancel();
}
public static void myMute() {
ten.setVolume(0, 0);
three.setVolume(0, 0);
}
public static void unMute() {
ten.setVolume(1, 1);
three.setVolume(1, 1);
}
#Override
public void onDestroy() {
stopSelf();
super.onDestroy();
}
}
_______________________________________________________________________________________________________________________________
Here is the method in Main_Menu (x starts as zero)
if ((x%2) == 0) { //If it's even
TwentySeconds.unMute();
Toast.makeText(Main_Menu.this, "UNMUTED", Toast.LENGTH_SHORT).show();
x++;
} else { //If its odd
TwentySeconds.myMute();
Toast.makeText(Main_Menu.this, "MUTED", Toast.LENGTH_SHORT).show();
x++;
}
__________________________________________________________________
Here is the stack trace:
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3842)
at android.view.View.performClick(View.java:4457)
at android.view.View$PerformClick.run(View.java:18491)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5272)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:883)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3837)
at android.view.View.performClick(View.java:4457)
at android.view.View$PerformClick.run(View.java:18491)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5272)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:883)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.USERNAME.buttonsmasher.TwentySeconds.myMute(TwentySeconds.java:106)
at com.example.USERNAME.buttonsmasher.Main_Menu.mute(Main_Menu.java:103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3837)
at android.view.View.performClick(View.java:4457)
at android.view.View$PerformClick.run(View.java:18491)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5272)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:883)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
at dalvik.system.NativeStart.main(Native Method)
I would really appreciate any feedback (positive or negative)!
Let me know if you need any thing else. Thanks so much for everything, I hope I can solve this issue... :)

Related

Android: finish() Activity Runtime Exception

I am closing an activity via finish().
It works fine on several devices but on a Samsung Galaxy S3 Neo running Android 4.4 I get the following issue:
java.lang.RuntimeException
android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3706)
android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:3724)
android.app.ActivityThread.access$1500(ActivityThread.java:169)
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1330)
android.os.Handler.dispatchMessage(Handler.java:102)
android.os.Looper.loop(Looper.java:136)
android.app.ActivityThread.main(ActivityThread.java:5476)
java.lang.reflect.Method.invokeNative(Native Method)
java.lang.reflect.Method.invoke(Method.java:515)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
dalvik.system.NativeStart.main(Native Method)
Caused by: android.util.Log.println_native(Native Method)
android.util.Log.e(Log.java:307)
com.ads.adstimer.fragment.Registration.RegistrationActivity.onDestroy(RegistrationActivity.java:214)
android.app.Activity.performDestroy(Activity.java:5623)
android.app.Instrumentation.callActivityOnDestroy(Instrumentation.java:1123)
android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3693)
android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:3724)
android.app.ActivityThread.access$1500(ActivityThread.java:169)
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1330)
android.os.Handler.dispatchMessage(Handler.java:102)
android.os.Looper.loop(Looper.java:136)
android.app.ActivityThread.main(ActivityThread.java:5476)
java.lang.reflect.Method.invokeNative(Native Method)
java.lang.reflect.Method.invoke(Method.java:515)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
dalvik.system.NativeStart.main(Native Method)
I have found two posts about that subject: First, Second
But they did not help me.
My activity code. Note that I am using AppIntro:
public class RegistrationActivity extends AppIntro {
private AsyncTaskRegisterInBackground registerPushToken;
(...)
#Override
public void onDonePressed() {
(...)
if (regid.isEmpty()) {
registerPushToken = new AsyncTaskRegisterInBackground();
registerPushToken.setParams(activity, gcm, regid);
registerPushToken.execute();
}
(...)
}
#Override
public void onTaskCompleted(String responseRegid) {
try {
// load authToken from Server: JsonObjectRequest
builderOnFailureDialog = new MaterialDialog.Builder(activity)
.title(getResources().getString(R.string.registrierung_dialog_registrieren_failure_retry_title))
.content(onFailureDialogContent)
.positiveText(getResources().getString(R.string.registrierung_dialog_registrieren_failure_retry_positive_text))
.negativeText(getResources().getString(R.string.registrierung_dialog_registrieren_failure_retry_negative_text))
.onNegative(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(#NonNull MaterialDialog dialog, #NonNull DialogAction which) {
activity.finish();
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
onFailureDialog.dismiss();
onSuccessDialog.dismiss();
} catch (Exception e) {
Log.e("Activity.onDestroy()", e.getMessage());
}
}
}
Or is the reason for the problem the async task running in background?
call finish() inside runOnUiThread().
i.e.
replace
finish();
with
runOnUiThread(new Runnable() {
public void run() {
finish()
}
});

Android Studio can't find Resuorces

This is the error message which shows up when I run the apk on my virtual device.
05-03 13:00:03.652 2354-2354/de.hochrad.hochradapp I/art﹕ Not late-enabling -Xcheck:jni (already on)
05-03 13:00:05.966 2354-2354/de.hochrad.hochradapp D/AndroidRuntime﹕ Shutting down VM
05-03 13:00:05.970 2354-2354/de.hochrad.hochradapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: de.hochrad.hochradapp, PID: 2354
java.lang.RuntimeException: Unable to start activity ComponentInfo{de.hochrad.hochradapp/de.hochrad.hochradapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.widget.Toast.<init>(Toast.java:101)
at android.widget.Toast.makeText(Toast.java:250)
at de.hochrad.hochradapp.MainActivity.onCreate(MainActivity.java:26)
at android.app.Activity.performCreate(Activity.java:5937)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
        at android.app.ActivityThread.access$800(ActivityThread.java:144)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5221)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
05-03 13:00:08.238 2354-2354/de.hochrad.hochradapp I/Process﹕ Sending signal. PID: 2354 SIG: 9
Somehow it cannot find the required Resources.
I hope you can help me!!!
Thx for all answers!!!
package de.hochrad.hochradapp;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
ArrayAdapter<String> klassen_adapter;
Vertretungsplan vertretungsplan;
Spinner klassen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(null, "Laden...", Toast.LENGTH_SHORT).show();
klassen_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
klassen = (Spinner) findViewById(R.id.klassenspinner);
Thread downloadThread = new Thread() {
public void run() {
vertretungsplan = new Vertretungsplan("1");
runOnUiThread(new Runnable() {
#Override
public void run() {
if (vertretungsplan.Ex != null) {
klassen_adapter.add("Fehler!");
} else {
klassen_adapter.add("Wähle deine Klasse!");
for (Klassenvertretung s : vertretungsplan.Klassen) {
klassen_adapter.add(s.Bezeichnung);
}
}
}
});
}
};
downloadThread.start();
klassen.setAdapter(klassen_adapter);
klassen.setSelection(0);
klassen.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(parent.getContext(),
"Deine Auswahl ist:" + parent.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
#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);
}
}
package de.hochrad.hochradapp;
import java.util.ArrayList;
import java.util.List;
public class Klassenvertretung {
public String Bezeichnung;
public List<Vertretung> Vertretungen = new ArrayList<Vertretung>();
public void Hinzufügen(Vertretung neuesElement) {
Vertretungen.add(neuesElement);
}
}
package de.hochrad.hochradapp;
public class Vertretung {
public String Klasse;
public String Stunde;
public String Art;
public String Fach;
public String Raum;
public String stattFach;
public String stattRaum;
public String Informationen;
}
package de.hochrad.hochradapp;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Vertretungsplan {
public Vertretungsplan(String woche) {
Woche = woche;
Einlesen(woche);
}
public String Woche;
public Exception Ex;
public List<Klassenvertretung> Klassen = new ArrayList<Klassenvertretung>();
private void Hinzufügen(Klassenvertretung neuesElement) {
Klassen.add(neuesElement);
}
private void Einlesen(String woche) {
try {
for (int webseite = 1; webseite < 10000; webseite++) {
Klassenvertretung klassenvertretung = new Klassenvertretung();
String teilseite = "0000";
if (webseite < 10)
teilseite = teilseite + "0";
teilseite = teilseite + webseite;
Connection connection = Jsoup
.connect("www.gymnasium-hochrad.de/Vertretungsplan/Vertretungsplan_Internet/"
+ woche + "/w/w" + teilseite + ".htm");
Document doc = connection.get();
Element h2 = doc.select("h2").get(0);
klassenvertretung.Bezeichnung = h2.text();
Element table = doc.select("table").get(1);
Element[] elemente = table.select("tr").toArray(new Element[0]);
for (int i = 1; i < elemente.length; i++) {
Element[] tds = elemente[i].select("td").toArray(
new Element[0]);
Vertretung vertretung = new Vertretung();
vertretung.Klasse = tds[0].text();
vertretung.Stunde = tds[1].text();
vertretung.Art = tds[2].text();
vertretung.Fach = tds[3].text();
vertretung.Raum = tds[4].text();
vertretung.stattFach = tds[5].text();
vertretung.stattRaum = tds[6].text();
vertretung.Informationen = tds[7].text();
klassenvertretung.Hinzufügen(vertretung);
}
Hinzufügen(klassenvertretung);
}
} catch (IOException io) {
if (Klassen.size() == 0) {
Ex = io;
}
} finally {
}
}
}
okay here is my code. I am form germany and so lots of Names are german (i hope thats not a problem.
Maybe it helps.
I guess the error must be in the main activity in one of the toasts. But dont hesitate to look at the other lines.
A/c to logcat error your are getting null reference error. try to update this line
Toast.makeText(parent.getContext(),
"Deine Auswahl ist:" + parent.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show();
with the following code
Toast.makeText(MainActivity.this,
"Deine Auswahl ist:" + parent.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show();
You have not initialised your adapter namely "klassen_adapter" in your main activity. It's null and invoking any method on it will be null pointer exception

How do I pull a string from an array in Android?

I have an android app that is a streaming radio.
To change the radio stations, there is a drop down menu (based on a spinner) that allows the user to select the radio station and then it will load.
Problem: when I leave it as default, the first channel plays fine ...
when I try to chose another station, the app crashes.
I am using the new Android Studio.
I think that I am not getting the string for the URL from the array.
Can someone help me see what my mistake is??
Here is my code:
import android.annotation.TargetApi;
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
public class AndroidMediaPlayerExample extends Activity {
private MediaPlayer mediaPlayer;
public TextView songName, duration;
private double timeElapsed = 0, finalTime = 0;
private int forwardTime = 2000, backwardTime = 2000;
private Handler durationHandler = new Handler();
private SeekBar seekbar;
//String url = "http://radio.miraath.net:7000";
//String url = new String[]{"http://radio.miraath.net:7000", "http://radio.miraath.net:7010", "http://radio.miraath.net:7020", "http://radio.miraath.net:7030","http://radio.miraath.net:7040", };
String url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set the layout of the Activity
setContentView(R.layout.activity_main);
Spinner dropdown = (Spinner)findViewById(R.id.spinner1);
String[] items = new String[]{"Radio 1: Arabic", "Radio 2: Live Arabic", "Radio 3: Qur'an", "Radio 4: English Radio", "Radio 5: Arabic Radio 2"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items);
dropdown.setAdapter(adapter);
//initialize views
initializeViews();
}
public void initializeViews(){
songName = (TextView) findViewById(R.id.songName);
mediaPlayer = MediaPlayer.create(this, R.raw.sample_song);
finalTime = mediaPlayer.getDuration();
duration = (TextView) findViewById(R.id.songDuration);
seekbar = (SeekBar) findViewById(R.id.seekBar);
songName.setText("Radio1 - Miraath.net");
seekbar.setMax((int) finalTime);
seekbar.setClickable(false);
}
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
mediaPlayer.release();
switch (position) {
case 0:
// Whatever you want to happen when the first item gets selected
url = "http://radio.miraath.net:7000";
break;
case 1:
// Whatever you want to happen when the second item gets selected
url = "http://radio.miraath.net:7010";
break;
case 2:
// Whatever you want to happen when the thrid item gets selected
url = "http://radio.miraath.net:7020";
break;
case 3:
// Whatever you want to happen when the thrid item gets selected
url = "http://radio.miraath.net:7030";
break;
case 4:
// Whatever you want to happen when the thrid item gets selected
url = "http://radio.miraath.net:7040";
break;
}
}
// play mp3 song
public void play(View view) {
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(url);
} catch (IllegalArgumentException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (SecurityException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IllegalStateException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
}
mediaPlayer.start();
timeElapsed = mediaPlayer.getCurrentPosition();
seekbar.setProgress((int) timeElapsed);
durationHandler.postDelayed(updateSeekBarTime, 100);
}
//handler to change seekBarTime
private Runnable updateSeekBarTime = new Runnable() {
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public void run() {
//get current position
timeElapsed = mediaPlayer.getCurrentPosition();
//set seekbar progress
seekbar.setProgress((int) timeElapsed);
//set time remaing
double timeRemaining = finalTime - timeElapsed;
duration.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes((long) timeRemaining), TimeUnit.MILLISECONDS.toSeconds((long) timeRemaining) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) timeRemaining))));
//repeat yourself that again in 100 miliseconds
durationHandler.postDelayed(this, 100);
}
};
// pause mp3 song
public void pause(View view) {
mediaPlayer.pause();
}
// go forward at forwardTime seconds
public void forward(View view) {
//check if we can go forward at forwardTime seconds before song endes
if ((timeElapsed + forwardTime) <= finalTime) {
timeElapsed = timeElapsed + forwardTime;
//seek to the exact second of the track
mediaPlayer.seekTo((int) timeElapsed);
}
}
// go backwards at backwardTime seconds
public void rewind(View view) {
//check if we can go back at backwardTime seconds after song starts
if ((timeElapsed - backwardTime) > 0) {
timeElapsed = timeElapsed - backwardTime;
//seek to the exact second of the track
mediaPlayer.seekTo((int) timeElapsed);
}
}
}
UPDATE!!!
Here is the error from the log:
03-14 19:20:10.413 1191-1284/system_process W/AudioTrack﹕ AUDIO_OUTPUT_FLAG_FAST denied by client
03-14 19:20:10.422 1191-1416/system_process I/ActivityManager﹕ START u0 {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.javacodegeeks.androidmediaplayerexample/.AndroidMediaPlayerExample (has extras)} from uid 10008 on display 0
03-14 19:20:10.457 4043-4043/? E/libprocessgroup﹕ failed to make and chown /acct/uid_10065: Read-only file system
03-14 19:20:10.457 4043-4043/? W/Zygote﹕ createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?
03-14 19:20:10.457 4043-4043/? I/art﹕ Not late-enabling -Xcheck:jni (already on)
03-14 19:20:10.461 1191-3310/system_process I/ActivityManager﹕ Start proc com.javacodegeeks.androidmediaplayerexample for activity com.javacodegeeks.androidmediaplayerexample/.AndroidMediaPlayerExample: pid=4043 uid=10065 gids={50065, 9997, 3003} abi=x86
03-14 19:20:10.493 4043-4050/? E/art﹕ Failed sending reply to debugger: Broken pipe
03-14 19:20:10.493 4043-4050/? I/art﹕ Debugger is no longer active
03-14 19:20:10.515 4043-4043/? D/AndroidRuntime﹕ Shutting down VM
03-14 19:20:10.515 4043-4043/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.javacodegeeks.androidmediaplayerexample, PID: 4043
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.javacodegeeks.androidmediaplayerexample/com.javacodegeeks.androidmediaplayerexample.AndroidMediaPlayerExample}: java.lang.ClassCastException: com.javacodegeeks.androidmediaplayerexample.AndroidMediaPlayerExample cannot be cast to android.widget.AdapterView$OnItemSelectedListener
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.ClassCastException: com.javacodegeeks.androidmediaplayerexample.AndroidMediaPlayerExample cannot be cast to android.widget.AdapterView$OnItemSelectedListener
at com.javacodegeeks.androidmediaplayerexample.AndroidMediaPlayerExample.onCreate(AndroidMediaPlayerExample.java:42)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Thanks!!
You have not added listener on your spinner. Do it in this manner after your adapter is set
dropdown.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
Also you activity has to implement OnItemSelectedListener
public class AndroidMediaPlayerExample extends Activity implements OnItemSelectedListener

Android: Google play games services connection error ( java.lang.IllegalStateException: GoogleApiClient must be connected.)

I've programmed a game for android, everything works fine, but now I want my app to have Google play Games services (leaderboards and achievements). I used the Google example code to log in to the Google services (no errors in the script), but every time I want to connect with my App in debug mode, I get this error:
6-29 11:48:29.391 23779-23779/com.JFKGames.theepicbutton E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.JFKGames.theepicbutton, PID: 23779
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=9001, result=10004, data=null} to activity {com.JFKGames.theepicbutton/com.JFKGames.theepicbutton.MainActivity}: java.lang.IllegalStateException: GoogleApiClient must be connected.
at android.app.ActivityThread.deliverResults(ActivityThread.java:3446)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3489)
at android.app.ActivityThread.access$1300(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1258)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5102)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalStateException: GoogleApiClient must be connected.
at com.google.android.gms.internal.fq.a(Unknown Source)
at com.google.android.gms.games.Games.c(Unknown Source)
at com.google.android.gms.games.internal.api.LeaderboardsImpl.submitScore(Unknown Source)
at com.google.android.gms.games.internal.api.LeaderboardsImpl.submitScore(Unknown Source)
at com.JFKGames.theepicbutton.MainActivity.onActivityResult(MainActivity.java:79)
at android.app.Activity.dispatchActivityResult(Activity.java:5446)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3442)
            at android.app.ActivityThread.handleSendResult(ActivityThread.java:3489)
            at android.app.ActivityThread.access$1300(ActivityThread.java:139)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1258)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5102)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
            at dalvik.system.NativeStart.main(Native Method)
And the App crashes. Here's my code for the MainActivity where I want it to connect:
public class MainActivity extends BaseGameActivity implements
GameHelper.GameHelperListener, View.OnClickListener {
public static int REQUEST_LEADERBOARD = 1002;
boolean mExplicitSignOut = false;
boolean mInSignInFlow = false;
GoogleApiClient mClient() {
return null;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
setRequestedClients(BaseGameActivity.CLIENT_GAMES | BaseGameActivity.CLIENT_APPSTATE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button)findViewById(R.id.startbutton);
button.setOnClickListener (this);
Button highscorebutton = (Button)findViewById(R.id.highscorebutton);
highscorebutton.setOnClickListener(this);
findViewById(R.id.sign_in_button).setOnClickListener(this);
findViewById(R.id.sign_out_button).setOnClickListener(this);
}
public void onClick(View view) {
if(view.getId()==R.id.startbutton) {
startActivityForResult(new Intent(this, buttonActivity.class), 1);
} else if(view.getId()==R.id.highscorebutton) {
startActivityForResult(Games.Leaderboards.getLeaderboardIntent(getApiClient(), getString(R.string.the_best_players)),REQUEST_LEADERBOARD);
} else if (view.getId() == R.id.sign_in_button) {
// start the asynchronous sign in flow
beginUserInitiatedSignIn();
}
else if (view.getId() == R.id.sign_out_button) {
// sign out.
signOut();
// show sign-in button, hide the sign-out button
findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
findViewById(R.id.sign_out_button).setVisibility(View.GONE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Games.Leaderboards.submitScore(getApiClient(), getString(R.string.the_best_players), resultCode);
if(requestCode==1) {
if(resultCode > leseHighscore()) {
schreibeHighscore(resultCode);
}
}
}
#Override
public void onSignInFailed() {
findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
findViewById(R.id.sign_out_button).setVisibility(View.GONE);
}
#Override
public void onSignInSucceeded() {
View a = findViewById(R.id.highscorebutton);
a.setVisibility(View.VISIBLE);
View b = findViewById(R.id.button3);
b.setVisibility(View.VISIBLE);
findViewById(R.id.sign_in_button).setVisibility(View.GONE);
findViewById(R.id.sign_out_button).setVisibility(View.VISIBLE);
}
}
Thanks, GoogleWelt
According to the official documentation, "Before any operation is executed, the GoogleApiClient must be connected"
When the user in not connected(signed in) and clicks to show leaderboards or achievements, it results in the exception thrown. Modify your code for launching the leaderboard like this:
} else if(view.getId()==R.id.highscorebutton) {
if (isSignedIn())
startActivityForResult(Games.Leaderboards.getLeaderboardIntent(getApiClient(), getString(R.string.the_best_players)), REQUEST_LEADERBOARD);
else showAlert("Please sign in to view leaderboards");
}
Use the same logic for showing achievements:
if (isSignedIn())
startActivityForResult(Games.Achievements.getAchievementsIntent(getApiClient()), REQUEST_ACHIEVEMENT);
else showAlert("Please sign in to view achievements");
Check the part where you are getting ApiClient i.e. getApiClient().
Write the code below to see if GoogleApiClient is Connected or not.
GoogleApiClient mGoogleApiClient;
if(mGoogleApiClient.isConnected()){
// good
}else{
//connect it
mGoogleApiClient.connect(GoogleApiClient.SIGN_IN_MODE_OPTIONAL);
}

App crashes on starting new activity

I am developing an app with slide fragments. Everything works fine, app starts without problems. Problem happens in View.onClickListener. Here is a code of my single fragment section:
public static class ReceiveSectionFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.receive, container, false);
rootView.findViewById(R.id.bt_server_start)
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), Receive.class);
startActivity(intent);
}
});
return rootView;
}
}
Sliding to target layout - R.layout.receive works well. So no problem here. On R.id.bt_server_start button click class below is started:
package com.receive.bluereceive;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.CountDownTimer;
import android.os.Vibrator;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;
public class Receive extends Activity {
/**
* Default Serial-Port UUID
*/
private String myUUID = "00001101-0000-1000-8000-00805F9B34FB";
/**
* Default Bluetooth adapter on the device.
*/
private final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
/**
* Magic number used in the Bluetooth enabling request.
*/
public final int REQUEST_ENABLE_BT = 2;
/**
* The Server thread.
*/
private AcceptThread DeviceServer;
private NotificationCenter mNotificationCenter;
public final static String EXTRA_MESSAGE = "com.receive.intent.MESSAGE";
public final int BT_ENABLE_TIME = 35;
public final int BT_TIME_BTTIME = 1000 * BT_ENABLE_TIME;
public CountDownTimer BTCountDown;
public CountDownTimer MoveHistoryCountDown;
#Override
protected void onStart() {
super.onStart();
mNotificationCenter = new NotificationCenter();
/*
* Code responsible for calling method NotificationCenter() to print the incoming text to TextView field
*/
registerReceiver(mNotificationCenter, new IntentFilter(EXTRA_MESSAGE));
/*
* Start server on device
*/
ServerThread();
((Button) findViewById(R.id.bt_server_start)).setEnabled(false);
((Button) findViewById(R.id.bt_server_stop)).setEnabled(true);
}
public void ServerThread() {
DeviceServer = new AcceptThread();
DeviceServer.start();
}
private class AcceptThread extends Thread {
/*
* That TAG will appear in the log in Eclipse
*/
private final String ACC_TAG = AcceptThread.class.getName();
/*
* Bluetooth server socket
*/
private final BluetoothServerSocket mServerSocket;
public AcceptThread() {
/*
* Use a temporary object that is later assigned to mServerSocket, because mServerSocket is final
*/
BluetoothServerSocket tmp = null;
try {
/*
* MY_UUID is the app's UUID string, also used by the client code
*/
tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(ACC_TAG, UUID.fromString(myUUID));
} catch (IOException e) { }
mServerSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
/*
* Keep listening until exception occurs or a socket is returned
*/
while (true) {
try {
Log.i(ACC_TAG,"Listening for a connection nearby...");
socket = mServerSocket.accept();
Log.i(ACC_TAG, "Connected to " + socket.getRemoteDevice().getName());
} catch (IOException e) {
break;
}
/*
* If connection was accepted then proceed with code below
* If Bluetooth socket does not equal null proceed with string reading as know script knows that device is connected
* And if it is first ServerThread start,
*/
if (socket != null) {
try {
String message;
DataInputStream incoming = new DataInputStream(socket.getInputStream());
message = incoming.readUTF();
Intent actual = new Intent(EXTRA_MESSAGE);
actual.putExtra("Message", String.format("%s",message));
getBaseContext().sendBroadcast(actual);
} catch (IOException e) {
Log.e(ACC_TAG, "Error obtaining InputStream from socket");
e.printStackTrace();
}
try {
mServerSocket.close();
} catch (IOException e) { }
break;
}
}
}
/*
* Will cancel the listening socket, and cause the thread to finish
*/
public void cancel() {
try {
mServerSocket.close();
} catch (IOException e) { }
}
}
private Vibrator getVibrator() {
return (Vibrator) getSystemService(VIBRATOR_SERVICE);
}
/*
* NOTIFICATION CLASS, PRINTS THE RECEIVED MESSAGE
*/
public class NotificationCenter extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(EXTRA_MESSAGE)) {
int counter = 0;
ArrayList<String> historiaAL = new ArrayList<String>();
historiaAL.add(intent.getExtras().getString("Message"));
TextView actual = (TextView)findViewById(R.id.received_string);
actual.setText(historiaAL.get(counter));
TextView history = (TextView)findViewById(R.id.history_string);
String[] historiaA = historiaAL.toArray(new String[historiaAL.size()]);
for(int i = 0; i < historiaAL.size(); i++)
{
history.append(historiaA[i]);
history.append(" \n ");
}
getVibrator().vibrate(500);
MoveHistoryCountDown = new HistoryMove(5000,5);
MoveHistoryCountDown.start();
counter++;
}
}
}
public class HistoryMove extends CountDownTimer {
public HistoryMove (long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
TextView recent = (TextView)findViewById(R.id.received_string);
recent.setText(" ");
}
#Override
public void onTick(long millisUntilFinished) {
}
}
}
Everything is included in Manifest.xml. What I get from LogCat is this:
12-18 00:36:14.136: E/AndroidRuntime(29672): FATAL EXCEPTION: main
12-18 00:36:14.136: E/AndroidRuntime(29672): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.receive.bluereceive/com.receive.bluereceive.Receive}: java.lang.NullPointerException
12-18 00:36:14.136: E/AndroidRuntime(29672): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2308)
12-18 00:36:14.136: E/AndroidRuntime(29672): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2358)
12-18 00:36:14.136: E/AndroidRuntime(29672): at android.app.ActivityThread.access$600(ActivityThread.java:153)
12-18 00:36:14.136: E/AndroidRuntime(29672): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1247)
12-18 00:36:14.136: E/AndroidRuntime(29672): at android.os.Handler.dispatchMessage(Handler.java:99)
12-18 00:36:14.136: E/AndroidRuntime(29672): at android.os.Looper.loop(Looper.java:137)
12-18 00:36:14.136: E/AndroidRuntime(29672): at android.app.ActivityThread.main(ActivityThread.java:5227)
12-18 00:36:14.136: E/AndroidRuntime(29672): at java.lang.reflect.Method.invokeNative(Native Method)
12-18 00:36:14.136: E/AndroidRuntime(29672): at java.lang.reflect.Method.invoke(Method.java:511)
12-18 00:36:14.136: E/AndroidRuntime(29672): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
12-18 00:36:14.136: E/AndroidRuntime(29672): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
12-18 00:36:14.136: E/AndroidRuntime(29672): at dalvik.system.NativeStart.main(Native Method)
12-18 00:36:14.136: E/AndroidRuntime(29672): Caused by: java.lang.NullPointerException
12-18 00:36:14.136: E/AndroidRuntime(29672): at com.receive.bluereceive.Receive.onStart(Receive.java:68)
12-18 00:36:14.136: E/AndroidRuntime(29672): at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1164)
12-18 00:36:14.136: E/AndroidRuntime(29672): at android.app.Activity.performStart(Activity.java:5114)
12-18 00:36:14.136: E/AndroidRuntime(29672): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2271)
12-18 00:36:14.136: E/AndroidRuntime(29672): ... 11 more
Probably this is some rookie mistake but still, it has been an hour and I still can not crack that out.
Please no downgrade reputation, I really can not have it working even tho it might seems trivial.
EDIT: Full main code - http://pastebin.com/e4dyW8Th
I don't see setContentView called anywhere in your activity which would mean that findViewById returns null.
Add onCreate method to your activity and call setContentView to set your layout.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_activity);
}

Categories

Resources