Not getting desired value in "onActivityResult" - android

Warning
**07-07 15:24:25.021: WARN/ActivityManager(57): Activity is launching as a new task, so cancelling activity result.**
07-07 15:24:25.681: WARN/ActivityManager(57): Activity pause timeout for HistoryRecord{43cccce8 com.tcs.QuickNotes/.QuickNotesHome}
07-07 15:24:27.392: INFO/AudioPathIn onActivityResult(1370): onActivityResult
07-07 15:24:27.410: INFO/requestCode(1370): requestCode1
07-07 15:24:27.420: INFO/resultCode(1370): **resultCode0**
My code
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.i("AudioPathIn onActivityResult"," onActivityResult"+audioFilePath.getText().toString());
Log.i("requestCode ","requestCode"+requestCode);
Log.i("resultCode ","resultCode"+resultCode);
if(requestCode == 1)
{
if(resultCode == RESULT_OK)
{
Audioflag=1;
audioFilePath.setVisibility(View.VISIBLE);
String defaultToneStatus = data.getStringExtra("DefaultTone");
if(defaultToneStatus.equals("false"))
{
audioFilePath.setText(AudioRecorder.getFilePath());
}
else
{
defaultAudioToneFlag = 1;
audioFilePath.setText("-");
}
}else
{
Audioflag=0;
}
}
}
Its not entering the above code.
Result code is always 0;
Code from where control is being returned :
public class AudioRecorder extends Activity implements OnClickListener {
String p = null;
static String filePath,FlagFromEdit,primaryIdFromEdit;
static int pId;
static int audioFlag;
Intent intent;
CheckBox defaultRingtone;
MyRecorder recorder;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
/** Called when the activity is first created. */
super.onCreate(savedInstanceState);
setContentView(R.layout.voicenote);
audioFlag=0;
intent=getIntent();
p = intent.getStringExtra("primaryiid");
pId = (Integer.parseInt(p));
Log.v("p", "pid" +pId);
setResult(RESULT_CANCELED);
// FlagFromEdit=intent.getStringExtra("FlagFromEdit");
// primaryIdFromEdit=intent.getStringExtra("PrimaryId");
defaultRingtone = (CheckBox)findViewById(R.id.Cb_defaultRingtone);
defaultRingtone.setOnClickListener(this);
Button btn_record = (Button)findViewById(R.id.btn_record);
btn_record.setOnClickListener(btnListenerRecord);
Button btn_stop = (Button)findViewById(R.id.btn_stop);
btn_stop.setOnClickListener(btnListenerStop);
Button btn_play = (Button)findViewById(R.id.btn_play);
btn_play.setOnClickListener(btnListenerPlay);
Button btn_save = (Button)findViewById(R.id.btn_save);
btn_save.setOnClickListener(btnListenerSave);
}
private OnClickListener btnListenerRecord = new OnClickListener()
{
public void onClick(View v)
{
try
{
recorder = new MyRecorder("voice/" + pId + "");
recorder.start();
Toast.makeText(getBaseContext(),"Recording started !", Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
e.printStackTrace();
}
}
};
private OnClickListener btnListenerStop = new OnClickListener()
{
public void onClick(View v)
{
MediaPlayer mp = new MediaPlayer();
try
{
recorder.stop();
Toast.makeText(getBaseContext(),"Stop ! IsPlaying : " + mp.isPlaying(), Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
e.printStackTrace();
}
}
};
private OnClickListener btnListenerPlay = new OnClickListener()
{
public void onClick(View v)
{
MediaPlayer mp = new MediaPlayer();
try
{
mp.setDataSource("/sdcard/voice/"+ pId + ".3gp");// set data-source
mp.prepare();// prepare
mp.start();
Toast.makeText(getBaseContext(), "Playing File no : "+pId, Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
e.printStackTrace();
}
Toast.makeText(getBaseContext(), " Is playing ? : "+ mp.isPlaying(),
Toast.LENGTH_LONG).show();
}
};
private OnClickListener btnListenerSave = new OnClickListener()
{
public void onClick(View v)
{
try
{
// String fileName = "/sdcard/voice/"+ pId + ".3gp";
// Intent intentSave = new Intent(getBaseContext(),AddToDoList.class);
// intentSave.putExtra("SavedFile", fileName);
// intentSave.putExtra("CalledFrom", "AudioRecorder");
// startActivity(intentSave);
audioFlag=1;
Toast.makeText(AudioRecorder.this,"File saved successfully !",Toast.LENGTH_LONG).show();
Intent intent = new Intent();
intent.putExtra("DefaultTone", "false");
setResult(RESULT_OK,intent);
finish();
}
catch (Exception e)
{
e.printStackTrace();
}
}
};
public static int getAudioFlag()
{
return audioFlag;
}
public static String getFilePath()
{
filePath ="/sdcard/voice/"+ pId + ".3gp";
return filePath;
}
public static void playAudioFile(Context ctx,String pId)
{
MediaPlayer mp = new MediaPlayer();
try
{
Log.i("playaudiofile","file being played");
//Toast.makeText(ctx,"file being played",Toast.LENGTH_LONG).show();
Toast.makeText(ctx, "Playing File no : "+pId, Toast.LENGTH_LONG).show();
mp.setDataSource("/sdcard/voice/"+ pId + ".3gp");// set data-source
mp.prepare();// prepare
mp.start();
}
catch (Exception e)
{
Toast.makeText(ctx, " No file was assigned ", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Toast.makeText(AudioRecorder.this,"Default ringtone set !",Toast.LENGTH_LONG).show();
Intent intent = new Intent();
intent.putExtra("DefaultTone", "true");
setResult(RESULT_OK,intent);
finish();
}
}

As Pentium10 has noticed, you are calling setResult(RESULT_CANCELED); in
onCreate().
Calling setResult() makes a call to onActivityResult method.
The value of RESULT_CANCELLED is 0x00000000.
So just remove the call setResult from onCreate method

Related

Exchanging String between devices over Bluetooth

I am beginner and making my first project on android studio. I want to exchange a unique string between devices over Bluetooth without pairing whenever devices are near. Following is the code I tried but did not work. The code I mention is of scanning part only when click on scan it search for the device and exchange the keys but it is not working.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ON = (Button) findViewById(R.id.button3);
OFF = (Button) findViewById(R.id.button5);
Scan = (Button) findViewById(R.id.search);
myBT = BluetoothAdapter.getDefaultAdapter();
Interaction = (Button) findViewById(R.id.intr);
intentON = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
other = (TextView)findViewById(R.id.textView4);
bluelist = (ListView) findViewById(R.id.btList);
//IntView = (ListView) findViewById(R.id.InList);
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
pAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
bluelist.setAdapter(arrayAdapter);
random = UUID.randomUUID();
getUUID = random.toString();
code = (TextView) findViewById(R.id.textView6);
data = getIntent().getExtras().getString("SomeNumbers");
code.setText(data);
send = (String) code.getText();
checkPermission();
ON.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(myBT.isEnabled())
Toast.makeText(getApplicationContext(), "Bluetooth already Enabled", Toast.LENGTH_SHORT).show();
else
bluetoothOn();
}
});
OFF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bluetoothOff();
}
});
Scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
discover();
}
});
bluelist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//pairDevice(device);
}
});
Interaction.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent getInteractions = new Intent(MainActivity.this, Interactions.class);
//Bundle args = new Bundle();
//args.putSerializable("Exposure", (Serializable)arrayList);
getInteractions.putStringArrayListExtra("Exposure", arrayList);
startActivity(getInteractions);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == BLUETOOTH_REQ_CODE) {
if (resultCode == RESULT_OK) {
Toast.makeText(getApplicationContext(), "Bluetooth is Enabled", Toast.LENGTH_LONG).show();
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(getApplicationContext(), "Bluetooth Disabled", Toast.LENGTH_LONG).show();
}
}
}
private void discover(){
if(myBT.isDiscovering()){
myBT.cancelDiscovery();
Toast.makeText(getApplicationContext(),"Discovery stopped",Toast.LENGTH_SHORT).show();
}
else{
if(myBT.isEnabled()) {
arrayAdapter.clear(); // clear items
myBT.startDiscovery();
Toast.makeText(getApplicationContext(), "Discovery started", Toast.LENGTH_SHORT).show();
registerReceiver(receiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
else{
bluetoothOn();
}
}
}
private final BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// add the name to the list
arrayAdapter.add(device.getName() + "\n" + device.getAddress());
arrayAdapter.notifyDataSetChanged();
ServerClass serverClass = new ServerClass();
serverClass.start();
ClientClass clientClass = new ClientClass(pairing);
clientClass.start();
sendReceive.write(send.getBytes());
}
}
};
Handler handler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(#NonNull Message msg) {
switch(msg.what)
{
case STATE_LISTENING:
Toast.makeText(getApplicationContext(), "Listening", Toast.LENGTH_SHORT).show();
break;
case STATE_CONNECTING:
Toast.makeText(getApplicationContext(), "Connecting", Toast.LENGTH_SHORT).show();
break;
case STATE_CONNECTED:
Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_SHORT).show();
break;
case STATE_CONNECTION_FAILED:
Toast.makeText(getApplicationContext(), "Connection Failed", Toast.LENGTH_SHORT).show();
break;
case STATE_MESSAGE_RECEIVED:
byte[] readBuff = (byte[]) msg.obj ;
String tempMsg = new String(readBuff,0,msg.arg1);
other.setText(tempMsg);
break;
}
return false;
}
});
private class ServerClass extends Thread
{
private BluetoothServerSocket serverSocket;
public ServerClass()
{
try {
serverSocket = myBT.listenUsingInsecureRfcommWithServiceRecord(App_Name,random);
} catch (IOException e) {
e.printStackTrace();
}
}
public void run()
{
BluetoothSocket socket=null;
while(socket == null)
{
try {
//Message msg = Message.obtain();
//msg.what=
//handler.sendMessage(msg);
socket=serverSocket.accept();
} catch (IOException e) {
e.printStackTrace();
//Message msg = Message.obtain();
//msg.what=
//handler.sendMessage(msg);
}
if(socket != null)
{
//Message msg = Message.obtain();
//msg.what=
//handler.sendMessage(msg);
sendReceive = new SendReceive(socket);
sendReceive.start();
break;
}
}
}
}
private class ClientClass extends Thread
{
private BluetoothDevice device;
private BluetoothSocket socket;
public ClientClass(BluetoothDevice device1)
{
device=device1;
try {
socket = device.createRfcommSocketToServiceRecord(random);
} catch (IOException e) {
e.printStackTrace();
}
}
public void run()
{
try {
socket.connect();
sendReceive = new SendReceive(socket);
sendReceive.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private class SendReceive extends Thread
{
private final BluetoothSocket bluetoothSocket;
private final InputStream inputStream;
private final OutputStream outputStream;
public SendReceive(BluetoothSocket socket)
{
bluetoothSocket=socket;
InputStream tempIn = null;
OutputStream tempOut = null;
try {
tempIn = bluetoothSocket.getInputStream();
tempOut = bluetoothSocket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
inputStream = tempIn;
outputStream = tempOut;
}
public void run()
{
byte[] buffer = new byte[1024];
int bytes;
while(true)
{
try {
bytes = inputStream.read(buffer);
handler.obtainMessage(STATE_MESSAGE_RECEIVED,bytes,-1,buffer).sendToTarget();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void write(byte[] bytes)
{
try {
outputStream.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}

Closing application undoes last action

I have an alarm clock application, and I've just added code to exit the program when using the Back button from the main activity. However, when I do so, the last action the user took is undone. For example, if the user creates three alarms, then presses the back button, only two alarms will show up.
This is the Back button code, from Main Activity:
#Override
public void onBackPressed() {
moveTaskToBack(true);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
And just in case, here's all the code from both activities I'm testing:
MainActivity.java (The only activity that has this Back button functionality, deliberately)
public class MainActivity extends AppCompatActivity {
ListView alarmListView;
ArrayList<Alarm> alarmList = new ArrayList<Alarm>();
AlarmAdapter alarmAdapter;
String filename = "alarmList";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
alarmListView = findViewById(R.id.alarmListView);
// Credit to Mitch Woodbright for helping with this section, and other try/catch blocks.
try
{
ArrayList<Alarm> alarm = (ArrayList<Alarm>) getIntent().getSerializableExtra("alarmList");
for(Alarm elements : alarm){
alarmList.add(elements);
}
writeAlarmList(alarmList);
}
catch (NullPointerException e){
System.out.println("AlarmList is empty.");
}
try {
alarmList = readAlarmList();
}
catch (NullPointerException e) {
}
alarmAdapter = new AlarmAdapter(MainActivity.this, alarmList){
#Override
public void onUpdateClick(int position, ArrayList<Alarm> alarmList) {
super.onUpdateClick(position, alarmList);
Intent updateAlarmIntent = new Intent(MainActivity.this,
CreateAlarmActivity.class);
updateAlarmIntent.putExtra("alarmList", alarmList);
updateAlarmIntent.putExtra("position", position);
startActivity(updateAlarmIntent);
}
};
alarmListView.setAdapter(alarmAdapter);
alarmAdapter.notifyDataSetChanged();
alarmListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent updateAlarmIntent = new Intent(MainActivity.this, CreateAlarmActivity.class);
updateAlarmIntent.putExtra("alarmList", alarmList);
updateAlarmIntent.putExtra("position", position);
startActivity(updateAlarmIntent);
}
});
// writeAlarmList(alarmList);
}
protected void onStart() {
super.onStart();
alarmList = readAlarmList();
}
protected void onResume() {
super.onResume();
alarmList = readAlarmList();
}
protected void onPause() {
super.onPause();
writeAlarmList(alarmList);
}
protected void onStop() {
super.onStop();
writeAlarmList(alarmList);
}
#Override
public void onBackPressed() {
// Thanks to Mitch for this line.
moveTaskToBack(true);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
// Create alarm when user presses FAB on activity_main.xml.
public void createNewAlarm(View view) {
Intent createAlarmIntent = new Intent(this, CreateAlarmActivity.class);
createAlarmIntent.putExtra("alarmList", alarmList);
startActivity(createAlarmIntent);
}
public void testAlarmActivated(View view){
//Intent activateAlarmIntent = new Intent(this, AlarmActivatedActivity.class);
//startActivity(activateAlarmIntent);
while(alarmList.size() > 0){
alarmList.remove(0);
}
Intent deleteEverythingIntent = new Intent(MainActivity.this, MainActivity.class);
deleteEverythingIntent.putExtra("alarmList", alarmList);
startActivity(deleteEverythingIntent);
}
public void writeAlarmList(ArrayList<Alarm> alarmList){
try {
FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(alarmList);
oos.close();
}
catch (FileNotFoundException e){
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
public ArrayList<Alarm> readAlarmList(){
try {
FileInputStream fis = openFileInput(filename);
ObjectInputStream ois = new ObjectInputStream(fis);
ArrayList<Alarm> alarmList = (ArrayList<Alarm>) ois.readObject();
ois.close();
return alarmList;
}
catch (FileNotFoundException e) {
ArrayList<Alarm> alarmList = new ArrayList<Alarm>();
System.out.println("File not found. Making empty list.");
return alarmList;
}
catch (IOException e) {
e.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (NullPointerException e) {
ArrayList<Alarm> alarmList = new ArrayList<Alarm>();
System.out.println("Null pointer exception. Making empty list.");
return alarmList;
}
ArrayList<Alarm> alarmList = new ArrayList<Alarm>();
return alarmList;
}
}
CreateAlarmActivity.java (The activity which does the creating/updating/deleting of alarms)
public class CreateAlarmActivity extends AppCompatActivity {
// If the alarm is being created, position = -1.
int position = -1;
int alarmHour;
int alarmMinute;
boolean isPm;
int snoozeTimer;
int[] daysActive;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_alarm);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
alarmList = (ArrayList<Alarm>)getIntent().getSerializableExtra("alarmList");
try {
// If we're updating an alarm, return the position of the alarm to update.
position = (int)getIntent().getSerializableExtra("position");
}
// Else, keep going.
catch (NullPointerException e){
}
Button hourButton = findViewById(R.id.buttonHours);
Button minuteButton = findViewById(R.id.buttonMinutes);
Button isPmButton = findViewById(R.id.buttonAmPm);
Button snoozeTimerButton = findViewById(R.id.buttonSnoozeTimer);
Button sundayButton = findViewById(R.id.buttonSunday);
Button mondayButton = findViewById(R.id.buttonMonday);
Button tuesdayButton = findViewById(R.id.buttonTuesday);
Button wednesdayButton = findViewById(R.id.buttonWednesday);
Button thursdayButton = findViewById(R.id.buttonThursday);
Button fridayButton = findViewById(R.id.buttonFriday);
Button saturdayButton = findViewById(R.id.buttonSaturday);
// If creating a new alarm, initialise data as default.
if (position == -1){
alarmHour = 6;
alarmMinute = 0;
isPm = false;
snoozeTimer = 10;
daysActive = new int[] {0, 0, 0, 0, 0, 0, 0};
}
// If updating an alarm, grab the defaults we already had.
else {
Alarm tempAlarm = alarmList.get(position);
alarmHour = tempAlarm.hour;
alarmMinute = tempAlarm.minute;
isPm = tempAlarm.isPm;
snoozeTimer = tempAlarm.snoozeTimer;
daysActive = tempAlarm.daysActive;
}
// Set buttons to what they should be.
hourButton.setText(Integer.toString(alarmHour));
snoozeTimerButton.setText(Integer.toString(snoozeTimer));
if (alarmMinute < 10){
minuteButton.setText("0" + Integer.toString(alarmMinute));
}
else {
minuteButton.setText(Integer.toString(alarmMinute));
}
if (!isPm){
isPmButton.setText("am");
}
else {
isPmButton.setText("pm");
}
setDayColor(sundayButton, daysActive[0]);
setDayColor(mondayButton, daysActive[1]);
setDayColor(tuesdayButton, daysActive[2]);
setDayColor(wednesdayButton, daysActive[3]);
setDayColor(thursdayButton, daysActive[4]);
setDayColor(fridayButton, daysActive[5]);
setDayColor(saturdayButton, daysActive[6]);
}
ArrayList<Alarm> alarmList = new ArrayList<Alarm>();
// Add one to the hour of the alarm.
public void changeHour(View view) {
Button btn = findViewById(R.id.buttonHours);
if (alarmHour == 12){
alarmHour = 0;
}
else {
alarmHour++;
}
btn.setText(Integer.toString(alarmHour));
}
// Add one to the minute of the alarm.
public void changeMinute(View view) {
Button btn = findViewById(R.id.buttonMinutes);
if (alarmMinute == 59) {
alarmMinute = 0;
}
else {
alarmMinute++;
}
if (alarmMinute < 10) {
// Ensure minute 1 becomes 01, e.g, 6:01 am.
btn.setText("0" + Integer.toString(alarmMinute));
}
else {
btn.setText(Integer.toString(alarmMinute));
}
}
public void changeAmPm(View view) {
Button btn = findViewById(R.id.buttonAmPm);
if (isPm == true) {
isPm = false;
btn.setText("am");
}
else {
isPm = true;
btn.setText("pm");
}
}
public void changeSnoozeTimer(View view) {
Button btn = findViewById(R.id.buttonSnoozeTimer);
if (snoozeTimer == 15){
snoozeTimer = 1;
}
else {
snoozeTimer++;
}
btn.setText(Integer.toString(snoozeTimer));
}
public void finishAlarm(View view){
EditText alarmName = findViewById(R.id.alarmName);
String name = alarmName.getText().toString();
Alarm alarm = new Alarm(name, alarmHour, alarmMinute, isPm, daysActive, snoozeTimer);
// If we're creating an alarm.
if (position == -1) {
try {
alarmList.add(alarm);
} catch (Exception e) {
}
}
// Else, we're updating one.
else {
try {
// Set the alarm we're updating to the new alarm.
alarmList.set(position, alarm);
} catch (Exception e) {
}
}
Intent finishAlarmIntent = new Intent(this, MainActivity.class);
finishAlarmIntent.putExtra("alarmList", alarmList);
startActivity(finishAlarmIntent);
}
public void cancelAlarm(View view){
Intent cancelAlarmIntent = new Intent(this, MainActivity.class);
cancelAlarmIntent.putExtra("alarmList", alarmList);
startActivity(cancelAlarmIntent);
}
public void deleteAlarm(View view) {
// If creating a new alarm, deleting is the same as cancelling.
if (position == -1) {
Intent cancelAlarmIntent = new Intent(this, MainActivity.class);
cancelAlarmIntent.putExtra("alarmList", alarmList);
startActivity(cancelAlarmIntent);
}
else {
// Remove the alarm.
alarmList.remove(position);
Intent cancelAlarmIntent = new Intent(this, MainActivity.class);
cancelAlarmIntent.putExtra("alarmList", alarmList);
startActivity(cancelAlarmIntent);
}
}
public void changeSunday(View view) {
Button btn = findViewById(R.id.buttonSunday);
daysActive[0] = switchDay(daysActive[0]);
setDayColor(btn, daysActive[0]);
}
public void changeMonday(View view) {
Button btn = findViewById(R.id.buttonMonday);
daysActive[1] = switchDay(daysActive[1]);
setDayColor(btn, daysActive[1]);
}
public void changeTuesday(View view) {
Button btn = findViewById(R.id.buttonTuesday);
daysActive[2] = switchDay(daysActive[2]);
setDayColor(btn, daysActive[2]);
}
public void changeWednesday(View view) {
Button btn = findViewById(R.id.buttonWednesday);
daysActive[3] = switchDay(daysActive[3]);
setDayColor(btn, daysActive[3]);
}
public void changeThursday(View view) {
Button btn = findViewById(R.id.buttonThursday);
daysActive[4] = switchDay(daysActive[4]);
setDayColor(btn, daysActive[4]);
}
public void changeFriday(View view) {
Button btn = findViewById(R.id.buttonFriday);
daysActive[5] = switchDay(daysActive[5]);
setDayColor(btn, daysActive[5]);
}
public void changeSaturday(View view) {
Button btn = findViewById(R.id.buttonSaturday);
daysActive[6] = switchDay(daysActive[6]);
setDayColor(btn, daysActive[6]);
}
// Helper method to switch the daysActive from 0 to 1 or from 1 to 0.
public int switchDay(int day) {
if (day == 0){
return 1;
}
return 0;
}
// Helper method to set the color of a daysActive button when updating the alarm.
public void setDayColor(Button btn, int day) {
if (day == 1) {
// Source: https://stackoverflow.com/questions/2173936/how-to-set-background-color-of-a-view
// Credit goes to EddieB for the below line.
btn.getBackground().setColorFilter(Color.parseColor("#00ff00"), PorterDuff.Mode.DARKEN);
} else {
// Source: https://stackoverflow.com/questions/14802354/how-to-reset-a-buttons-background-color-to-default
// Credit goes to Ivo for the below line.
btn.getBackground().clearColorFilter();
}
}
}
For people from the future:
I ended up solving this by using the following:
#Override
public void onBackPressed() {
this.finishAffinity();
}
Source: How to quit android application programmatically

How to play an audio from soundcloud in our app.?

Following program allows user to upload an audio from app to SoundCloud.But what if i need to play an audio from my account in soundcloud in my app?How to play an audio from soundcloud or from particular url of soundclous to in our app ?
public class Record extends Activity {
public static final String TAG = "soundcloud-intent-sharing-example";
private boolean mStarted;
private MediaRecorder mRecorder;
private File mArtwork;
private static boolean AAC_SUPPORTED = Build.VERSION.SDK_INT >= 10;
private static final int PICK_ARTWORK = 1;
private static final int SHARE_SOUND = 2;
private static final File FILES_PATH = new File(
Environment.getExternalStorageDirectory(),
"Android/data/com.soundcloud.android.examples/files");
private static final File RECORDING = new File(
FILES_PATH,
"demo-recording" + (AAC_SUPPORTED ? ".mp4" : "3gp"));
private static final Uri MARKET_URI = Uri.parse("market://details?id=com.soundcloud.android");
private static final int DIALOG_NOT_INSTALLED = 0;
// Replace with the client id of your registered app!
// see http://soundcloud.com/you/apps/
private static final String CLIENT_ID = "fecfc092de134a960dc48e53c044ee91";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Environment.MEDIA_MOUNTED.equals(
Environment.getExternalStorageState())) {
if (!FILES_PATH.mkdirs()) {
Log.w(TAG, "Could not create " + FILES_PATH);
}
} else {
Toast.makeText(this, R.string.need_external_storage, Toast.LENGTH_LONG).show();
finish();
}
setContentView(R.layout.record);
final Button record_btn = (Button) findViewById(R.id.record_btn);
final Button share_btn = (Button) findViewById(R.id.share_btn);
final Button play_btn = (Button) findViewById(R.id.play_btn);
final Button artwork_btn = (Button) findViewById(R.id.artwork_btn);
Record last = getLastNonConfigurationInstance();
if (last != null) {
mStarted = last.mStarted;
mRecorder = last.mRecorder;
mArtwork = last.mArtwork;
record_btn.setText(mStarted ? R.string.stop : R.string.record);
}
record_btn.setOnClickListener(new View.OnClickListener() {
public synchronized void onClick(View v) {
if (!mStarted) {
Toast.makeText(Record.this, R.string.recording, Toast.LENGTH_SHORT).show();
mStarted = true;
mRecorder = getRecorder(RECORDING, AAC_SUPPORTED);
mRecorder.start();
record_btn.setText(R.string.stop);
} else {
Toast.makeText(Record.this, R.string.recording_stopped, Toast.LENGTH_SHORT).show();
mRecorder.stop();
mRecorder.release();
mRecorder = null;
mStarted = false;
record_btn.setText(R.string.record);
share_btn.setEnabled(true);
play_btn.setEnabled(true);
artwork_btn.setEnabled(true);
}
}
});
play_btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
play_btn.setEnabled(false);
record_btn.setEnabled(false);
share_btn.setEnabled(false);
play(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mediaPlayer) {
play_btn.setEnabled(true);
record_btn.setEnabled(true);
share_btn.setEnabled(true);
}
});
}
});
share_btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
shareSound();
}
});
artwork_btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivityForResult(new Intent(Intent.ACTION_GET_CONTENT).setType("image/*"), PICK_ARTWORK);
}
});
if (!isCompatibleSoundCloudInstalled(this)) {
showDialog(DIALOG_NOT_INSTALLED);
}
}
private void play(MediaPlayer.OnCompletionListener onCompletion) {
MediaPlayer player = new MediaPlayer();
try {
player.setDataSource(RECORDING.getAbsolutePath());
player.prepare();
player.setOnCompletionListener(onCompletion);
player.start();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
// the actual sharing happens here
private void shareSound() {
Intent intent = new Intent("com.soundcloud.android.SHARE")
.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(RECORDING))
// here you can set metadata for the track to be uploaded
.putExtra("com.soundcloud.android.extra.title", "SoundCloud Android Intent Demo upload")
.putExtra("com.soundcloud.android.extra.where", "Somewhere")
.putExtra("com.soundcloud.android.extra.description", "This is a demo track.")
.putExtra("com.soundcloud.android.extra.public", true)
.putExtra("com.soundcloud.android.extra.tags", new String[] {
"demo",
"post lolcat bluez",
"soundcloud:created-with-client-id="+CLIENT_ID
})
.putExtra("com.soundcloud.android.extra.genre", "Easy Listening")
.putExtra("com.soundcloud.android.extra.location", getLocation());
// attach artwork if user has picked one
if (mArtwork != null) {
intent.putExtra("com.soundcloud.android.extra.artwork", Uri.fromFile(mArtwork));
}
try {
startActivityForResult(intent, SHARE_SOUND);
} catch (ActivityNotFoundException notFound) {
// use doesn't have SoundCloud app installed, show a dialog box
showDialog(DIALOG_NOT_INSTALLED);
}
}
#Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case SHARE_SOUND:
// callback gets executed when the SoundCloud app returns
if (resultCode == RESULT_OK) {
Toast.makeText(this, R.string.shared_ok, Toast.LENGTH_SHORT).show();
} else {
// canceled
Toast.makeText(this, R.string.shared_canceled, Toast.LENGTH_SHORT).show();
}
break;
case PICK_ARTWORK:
if (resultCode == RESULT_OK) {
mArtwork = getFromMediaUri(getContentResolver(), data.getData());
}
break;
}
}
private MediaRecorder getRecorder(File path, boolean useAAC) {
MediaRecorder recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
if (useAAC) {
recorder.setAudioSamplingRate(44100);
recorder.setAudioEncodingBitRate(96000);
recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
} else {
// older version of Android, use crappy sounding voice codec
recorder.setAudioSamplingRate(8000);
recorder.setAudioEncodingBitRate(12200);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
}
recorder.setOutputFile(path.getAbsolutePath());
try {
recorder.prepare();
} catch (IOException e) {
throw new RuntimeException(e);
}
return recorder;
}
// just get the last known location from the passive provider - not terribly
// accurate but it's a demo app.
private Location getLocation() {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
return locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
}
#Override public Record getLastNonConfigurationInstance() {
return (Record) super.getLastNonConfigurationInstance();
}
#Override public Record onRetainNonConfigurationInstance() {
return this;
}
// Helper method to get file from a content uri
private static File getFromMediaUri(ContentResolver resolver, Uri uri) {
if ("file".equals(uri.getScheme())) {
return new File(uri.getPath());
} else if ("content".equals(uri.getScheme())) {
String[] filePathColumn = {MediaStore.MediaColumns.DATA};
Cursor cursor = resolver.query(uri, filePathColumn, null, null, null);
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
return new File(filePath);
}
} finally {
cursor.close();
}
}
}
return null;
}
private static boolean isCompatibleSoundCloudInstalled(Context context) {
try {
PackageInfo info = context.getPackageManager()
.getPackageInfo("com.soundcloud.android",
PackageManager.GET_META_DATA);
// intent sharing only got introduced with version 22
return info != null && info.versionCode >= 22;
} catch (PackageManager.NameNotFoundException e) {
// not installed at all
return false;
}
}
#Override
protected Dialog onCreateDialog(int id, Bundle data) {
if (DIALOG_NOT_INSTALLED == id) {
return new AlertDialog.Builder(this)
.setTitle(R.string.sc_app_not_found)
.setMessage(R.string.sc_app_not_found_message)
.setPositiveButton(android.R.string.yes, new Dialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent market = new Intent(Intent.ACTION_VIEW, MARKET_URI);
startActivity(market);
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
}).create();
} else {
return null;
}
}
}
knowing the url of the sound, you need to do the following:
resolve the URL in order to get the soundcloud API URL using Resolve endpoint
load the tracks API URL to get track representation in json or xml
initialise audio object and set the audio source to the value of stream_url property of track representation
The particular implementation varies depending on the libraries you use etc. But you'll definitely need to use HTTP requests, JSON parser and an audio object.

Android- listview, service mediaplayer, and boolean flags

I currently have a listview and when you click on an item it runs a service with a mediaplayer. If I click on another item in the listview the service that's running should stop and run the new service. I am using a boolean isRunning set to false and when the service is created it returns true. Then in the listview I call that flag in an if statement. However, its not exactly working. I think I may be doing this wrong. Any ideas?
This probably sounds confusing the way I described it so Here is the code to my listview and my service. I am only testing this on case 3 (so I press this item to start the service and then click on case 2 to see if it will stop it).
Listview class:
public class PlaylistActivity extends ListActivity{
private static final String TAG = PlaylistActivity.class.getSimpleName();
// Data to put in the ListAdapter
private String[] sdrPlaylistNames = new String[] {
"Best of June 2011", "Best of May 2011", "Dubstep",
"House", "Other"};
private ListAdapter sdrListAdapter;
Intent playbackServiceIntentBOJ, playbackServiceIntentBOM, playbackServiceIntentDUB;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playlists_layout);
//fill the screen with the list adapter
playlistFillData();
playbackServiceIntentDUB = new Intent(this, DUBAudioService.class);
Log.d(TAG, "Made DUB Service Intent");
}
public void playlistFillData() {
//create and set up the Array adapter for the list view
ArrayAdapter sdrListAdapter = new ArrayAdapter(this, R.layout.list_item, sdrPlaylistNames);
setListAdapter(sdrListAdapter);
}
//set up the on list item Click
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
//create a switch so that each list item is a different playlist
switch(position){
case 0:
Intent BOJintent = new Intent(this, BOJAudioActivity.class);
// Create the view using PlaylistGroup's LocalActivityManager
View view = PlaylistGroup.group.getLocalActivityManager()
.startActivity("show_city", BOJintent
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
.getDecorView();
// Again, replace the view
PlaylistGroup.group.replaceView(view);
// playbackServiceIntentBOJ = new Intent(this, BOJAudioService.class);
Log.d(TAG, "Made BOJ Intent");
// startService(playbackServiceIntentBOJ);
Log.d(TAG, "started BOJ Service");
break;
case 1:
Intent BOMintent = new Intent(this, BOMAudioActivity.class);
// Create the view using PlaylistGroup's LocalActivityManager
View view2 = PlaylistGroup.group.getLocalActivityManager()
.startActivity("show_city", BOMintent
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
.getDecorView();
// Again, replace the view
PlaylistGroup.group.replaceView(view2);
Log.d(TAG, "Replace view");
//getApplicationContext().stopService(playbackServiceIntentBOJ);
//playbackServiceIntentBOM = new Intent(this, BOJAudioService.class);
Log.d(TAG, "Made BOM Service Intent");
// startService(playbackServiceIntentBOM);
Log.d(TAG, "started BOM Service");
if(DUBAudioActivity.isRunningDUB = true){
stopService(playbackServiceIntentDUB);
Log.d(TAG, "stop service isRunningDUB");
}
//
break;
case 2:
Intent DUBIntent = new Intent (this, DUBAudioActivity.class);
View view3 = PlaylistGroup.group.getLocalActivityManager()
.startActivity("show_city", DUBIntent
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
.getDecorView();
PlaylistGroup.group.replaceView(view3);
Log.d(TAG, "Replace view");
startService(playbackServiceIntentDUB);
Log.d(TAG, "started DUB service");
break;
}
}
}
Service Class:
public class DUBAudioService extends Service implements OnPreparedListener, OnCompletionListener{
Toast loadingMessage;
private static final String TAG = DUBAudioService.class.getSimpleName();
public static boolean isRunningDUB = false;
//to keep track of the playlist item
Vector<PlaylistFile> playlistItems;
MediaPlayer mediaPlayer;
String baseURL = "";
//keep track of which item from the vector we are on
int currentPlaylistltemNumber = 0;
public class DUBBackgroundAudioServiceBinder extends Binder {
DUBAudioService getService() {
return DUBAudioService.this;
}
}
private final IBinder basBinderDUB = new DUBBackgroundAudioServiceBinder();
#Override
public IBinder onBind(Intent intent) {
return basBinderDUB;
}
#Override
public void onCreate() {
Log.v("PLAYERSERVICE", "onCreate");
mediaPlayer = new MediaPlayer();
new MusicAsync().execute();
Log.d(TAG, "execute'd async");
mediaPlayer.setOnPreparedListener(this);
Log.d(TAG, "set on prepared listener");
mediaPlayer.setOnCompletionListener(this);
Log.d(TAG, "set on completion listener");
isRunningDUB = true;
Log.d(TAG, "isRunningRUB = true");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//if (!mediaPlayer.isPlaying()) {
// mediaPlayer.start();
//}
return START_STICKY;
}
class MusicAsync extends AsyncTask<Void,Void,Void>{
#Override
protected void onPreExecute(){
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
//create empty vector
playlistItems = new Vector<PlaylistFile>();
//HTTP client library
HttpClient httpClient = new DefaultHttpClient();
HttpGet getRequest = new HttpGet ("http://dl.dropbox.com/u/24535120/m3u%20playlist/DubstepPlaylist.m3u"); //i think you could add the m3u thing in here
Log.v("URI",getRequest.getURI().toString());
try {
HttpResponse httpResponse = httpClient.execute(getRequest);
if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
// ERROR MESSAGE
Log.v("HTTP ERROR",httpResponse.getStatusLine().getReasonPhrase());
}
else {
InputStream inputStream = httpResponse.getEntity().getContent();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = bufferedReader.readLine()) != null) {
Log.v("PLAYLISTLINE","ORIG: " + line);
if (line.startsWith("#")) {
//Metadata
//Could do more with this but not fo now
} else if (line.length() > 0) {
String filePath = "";
if (line.startsWith("http://")) {
// Assume its a full URL
filePath = line;
} else {
//Assume it’s relative
filePath = getRequest.getURI().resolve(line).toString();
}
PlaylistFile playlistFile = new PlaylistFile(filePath);
playlistItems.add (playlistFile);
}
}
inputStream.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e. printStackTrace();
}
currentPlaylistltemNumber = 0;
if (playlistItems.size() > 0)
{
String path = ((PlaylistFile)playlistItems.get(currentPlaylistltemNumber)).getFilePath();
try {
mediaPlayer.setDataSource(path);
mediaPlayer.prepareAsync();}
catch (IllegalArgumentException e)
{ e.printStackTrace();
}catch (IllegalStateException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();}
}
return null;
}
//
protected void onPostExecute(Void result){
//playButton. setEnabled (false);
}
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
public void onDestroy() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
Log.d(TAG, "music stopp'd");
}
//mediaPlayer.release();
Log.d(TAG, "onDestroy");
}
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
// TODO Auto-generated method stub\
Log.d(TAG, "music is prepared and will start");
mediaPlayer.start();
}
public void onCompletion(MediaPlayer _mediaPlayer) {
Log.d(TAG, "Song completed, next song");
mediaPlayer.stop();
mediaPlayer.reset();
if (playlistItems.size() > currentPlaylistltemNumber + 1) {
currentPlaylistltemNumber++;
String path =
((PlaylistFile)playlistItems.get(currentPlaylistltemNumber)).getFilePath();
try {
mediaPlayer.setDataSource(path);
mediaPlayer.prepareAsync();
} catch (IllegalArgumentException e) {
e. printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class PlaylistFile {
String filePath;
public PlaylistFile(String _filePath) {
filePath = _filePath;
}
public void setFilePath(String _filePath) {
filePath = _filePath;
}
public String getFilePath() {
return filePath;
}
}
public void playSong(){
Log.d(TAG, "start'd");
mediaPlayer.start();
}
public void pauseSong(){
Log.d(TAG, "pause'd");
mediaPlayer.pause();
}
}
This gets pretty complicated but I used the following to see if my service was running:
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if ("com.example.MyService".equals(service.service.getClassName())) {
return true;
}
}
return false;
}
I added this in my listview class and put if statements in each case to see if it was running and if so would stop the service.
I also made my all of my binding conenctions public so that the listview class could access them and start them on click.
If anyone wants to further understand, etc message me.
let your app track the state, not your service.

Can't get song duration in onCreate , but can get it on button pressed

I have a custom media service and an audio player class which communicates with it but is not bound to the service.
When I create an object of MyService and write the code :-
myService.player.getDuration() in onCreate I get the null pointer exception on this line.
But if I write this code on click of some button listener on the same screen then I get the exact duration.
I have tried every possible syntax to solve this but m still not able to resolve the problem.
** The code of my service is :-**
private static final String TAG = "MyService";
public static MediaPlayer player;
String song_uri,url;
Bundle b;
private IBinder myBinder;
private boolean isplaying;
public static final String Song_uri="song_uri";
public static final String EXTRA_SHUFFLE="EXTRA_SHUFFLE";
#Override
public IBinder onBind(Intent intent) {
return null;
}
public class MyBinder extends Binder{
MyService getService()
{
return MyService.this;
}
}
#Override
public void onCreate() {
Log.d(TAG, "onCreate "+song_uri);
}
#Override
public void onDestroy() {
//Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
DataManager.getInstance().setWantsToPlaySong(false);
DataManager.getInstance().setCurrentPosition(0);
Log.d(TAG, "onDestroy");
player.stop();
//player.release();
}
public void onPause()
{
player.pause();
}
public double duration()
{
return player.getDuration();
}
public void onStart(Intent intent, int startid) {
DataManager.getInstance().setWantsToPlaySong(true);
Bundle b=intent.getExtras();
song_uri=b.getString("song_uri");
Uri path=Uri.parse(song_uri);
player = MediaPlayer.create(this,path );
player.setLooping(false); // Set looping
//Toast.makeText(this, "My Service Started"+" Duration = "+(player.getDuration()/1000)/60, Toast.LENGTH_SHORT).show();
Log.d(TAG, "onStart"+song_uri);
player.start();
}
The code of Audio Player is :-
uri = this.getIntent().getExtras().getString("song_uri");
buttonStart = (Button) findViewById(R.id.buttonStart);
buttonStop = (Button) findViewById(R.id.buttonStop);
buttonPause = (Button) findViewById(R.id.buttonPause);
tracks = dbManager.getAllSongs(AudioPlayer2.this);
buttonForward = (Button) findViewById(R.id.buttonforward);
buttonBackward = (Button) findViewById(R.id.buttonbackward);
//=========================================================================================
sArtworkUri = Uri.parse("content://media/external/audio/albumart");
//myservice=new MyService();
Uri path = Uri.parse(uri);
current_song=this.getIntent().getExtras().getInt("current_song");
albumArtUri = this.getIntent().getExtras().getString("album_art");
Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
album_id = Long.parseLong(this.getIntent().getStringExtra("album_id"));
int id = Integer.parseInt(this.getIntent().getStringExtra("album_id"));
albumImageUri = ContentUris.withAppendedId(sArtworkUri, album_id);
ivAlbumArt = (ImageView) findViewById(R.id.album_art);
songName = this.getIntent().getStringExtra("song_name");
albumName = this.getIntent().getStringExtra("album_name");
tvName = (TextView) findViewById(R.id.tv_name);
tvAlbum = (TextView) findViewById(R.id.tv_album);
if (songName != null) {
tvName.setText(songName);
}
if (albumName != null) {
tvAlbum.setText(albumName);
}
// buttonStart.performClick();
if (DataManager.getInstance().getOnPausedSong()=="y"){
//Toast.makeText(AudioPlayer2.this, "stage 1", Toast.LENGTH_SHORT).show();
if(DataManager.getInstance().getPausedSongName()==songName){
//Toast.makeText(AudioPlayer2.this, "stage 1", Toast.LENGTH_SHORT).show();
buttonStart.setVisibility(View.GONE);
buttonPause.setVisibility(View.VISIBLE);
}
}
FetchImage fetchImage = new FetchImage();
fetchImage.execute();
/*if(DataManager.getInstance().getSong_uri()!=null)
{
stopService(new Intent(this, MyService.class));
}*/
// if(myService.player.isPlaying())
//{
stopService(new Intent(this, MyService.class));
Intent intent = new Intent(this,MyService.class);
Bundle b = new Bundle();
b.putString("song_uri",uri );
intent.putExtras(b);
startService(intent);
myService.player.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
buttonStart.setVisibility(View.VISIBLE);
buttonPause.setVisibility(View.GONE);
}
});
buttonStart.setVisibility(View.GONE);
buttonPause.setVisibility(View.VISIBLE);
// Toast.makeText(this, "Duration: "+myService.player.getDuration(), Toast.LENGTH_LONG).show();
/*//}//DataManager.getInstance().setSong_uri(uri);
Intent intent = new Intent(this,MyService.class);
Bundle b = new Bundle();
b.putString("song_uri",uri );
intent.putExtras(b);
startService(intent);
buttonStart.setVisibility(View.GONE);
buttonPause.setVisibility(View.VISIBLE);
DataManager.getInstance().setSong_uri(uri);
DataManager.getInstance().setOnPausedSong("y");
DataManager.getInstance().setPausedSongName(songName);
*/ //buttonStart.setPressed(true);
//=======================================================================================
buttonStart.setOnClickListener(this);
buttonPause.setOnClickListener(this);
buttonForward.setOnClickListener(this);
buttonBackward.setOnClickListener(this);
buttonStop.setOnClickListener(this);
// buttonPause.performClick();
/* new Thread(myThread).start();
*/ }
// Thread for seekbar
// song starts playing
public void onClick(View src) {
switch (src.getId()) {
case R.id.buttonStart:
if(DataManager.getInstance().getSongPause()=="y"){
myService.player.start();
DataManager.getInstance().setSongPause("n");
buttonStart.setVisibility(View.GONE);
buttonPause.setVisibility(View.VISIBLE);
// DataManager.getInstance().setWantsToPlaySong(true);
//DataManager.getInstance().setOnPausedSong("n");
//DataManager.getInstance().setOnPausedSong("y");
}else{
stopService(new Intent(this, MyService.class));
DataManager.getInstance().setSong_uri(uri);
Intent intent = new Intent(this,MyService.class);
Bundle b = new Bundle();
b.putString("song_uri",uri );
intent.putExtras(b);
startService(intent);
buttonStart.setVisibility(View.GONE);
buttonPause.setVisibility(View.VISIBLE);
DataManager.getInstance().setOnPausedSong("y");
DataManager.getInstance().setPausedSongName(songName);
}
//Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
break;
case R.id.buttonStop:
Log.d(TAG, "onClick: stopping srvice");
stopService(new Intent(this, MyService.class));
buttonStart.setVisibility(View.VISIBLE);
buttonPause.setVisibility(View.GONE);
break;
case R.id.buttonforward:
stopService(new Intent(this, MyService.class));
current_song++;
FetchAllMusic fetchAllMusic = new FetchAllMusic();
fetchAllMusic.execute();
//new Thread(myThread).start();
break;
case R.id.buttonbackward:
Log.d(TAG, "onClick: stopping service");
stopService(new Intent(this, MyService.class));
if(current_song>0){
current_song--;
}
FetchAllMusic fetchAllMusic2 = new FetchAllMusic();
fetchAllMusic2.execute();
break;
case R.id.buttonPause:
buttonStart.setVisibility(View.VISIBLE);
buttonPause.setVisibility(View.GONE);
/* MyService myservice=new MyService();
myservice.onPause();*/
myService.player.pause();
DataManager.getInstance().setSongPause("y");
DataManager.getInstance().setWantsToPlaySong(false);
DataManager.getInstance().setOnPausedSong("n");
DataManager.getInstance().setPausedSongName(songName);
//duration=myService.player.getDuration();
// Toast.makeText(this, ""+duration, Toast.LENGTH_LONG).show();
}
}
public void onBackPressed() {
try {
//addvideo.removeView(DBManager.getInstance().getVideo());
DataManager.getInstance().setSong_uri(uri);
DataManager.getInstance().setAlbum_id(""+album_id);
DataManager.getInstance().setAlbumName(albumName);
DataManager.getInstance().setSongName(songName);
DataManager.getInstance().setAlbumArtUri(albumArtUri);
DataManager.getInstance().setCurrent_song(current_song);
DataManager.getInstance().setWantsToPlaySong(false);
} catch (Exception e) {
e.printStackTrace();
}
super.onBackPressed();
}
private Runnable myThread = new Runnable(){
#Override
public void run() {
Log.d(TAG, "Thread Starts");
// TODO Auto-generated method stub
while (myProgress<100){
try{
Log.d(TAG, "Thread Starts");
myHandle.sendMessage(myHandle.obtainMessage());
Thread.sleep(3000);
}
catch(Throwable t){
}
}
}
Handler myHandle = new Handler(){
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
myProgress++;
seekbar.setProgress(myProgress);
}
};
};
It's not a syntax problem; it's a variable initialization problem. Either myService or myService.player is null when that line executes in onCreate(). Check your code for where you are initializing these and make sure that you don't reference them before they are set.

Categories

Resources