Pass data from first activity to second activity to play song - android

How do I pass data between these activities because now I can play music in first activity when I click the list item,but now I want to pass data from first activity which contains list to second activity directly play song in second activity and also I am confuse about service because I am using service in my first activity when I play song in second activity what will be happen on service

You can do it adding extra data to the intent that starts 2nd activity.
For that your song class must implement Parcelable
public class Song implements Parcelable
{
string artist;
string songName;
string filePath;
#Override
public int describeContents()
{
return 0;
}
protected Song(Parcel in)
{
artist = in.readString();
songName = in.readString();
filePath = in.readString();
}
#Override
public void writeToParcel(Parcel dest, int flags)
{
dest.writeString(artist);
dest.writeString(songName);
dest.writeString(filePath);
}
}
And then when opening second activity to play song it would be like this:
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
intent.putExtra("song", songToPlay);
getApplicationContext().startActivity(intent);
For last you would receive the song in the 2nd activity as follows:
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.song_player);
Intent intent = getIntent();
if (intent != null)
{
if (intent.hasExtra("song"))
{
Song songToPlay = intent.getExtra("song");
}
}
}

Related

How to remove Specific activity/activities from activity stack based on some action?

I am working on an application where i need to navigate to specific activity based on some actions. Here is a image
Here my first activity is the ReadingActivity. Based on some actions user will be taken to the NewProjectReadingActivity. There the user will have Two options.
Option One
Option Two
Based on the options chosen by the user he/she will be taken to the ReadingInputActivity. After taking the input from the ReadingInputActivity the user will be forwarded to the ReadingConfirmationActivity. There will be three options
Option One
Option Two
Option Three
If the user selects the Option One then he/she will be taken to the ReadingActivity which is very easy. I will clear the stack and start the ReadingActivity again and there if he/she presses the back button the app will be minimized which is totally fine. But if the user selects Option Two then he/she will be taken to the NewProjectReadingActivity.If i clear the activity stack and start NewProjectReadingActivity again then it will start the NewProjectReadingActivity but the problem is that if the user presses the back button it will minimize my app as it is the only Activity present in the activity stack.
What i want is that if the user selects Option Two on the ReadingConfirmationActivity then the user will be taken to the NewReadingActivity that means i want to remove ReadingConfirmationActivity (which is easy just call the finish()) and the activity started before that activity i,e ReadingInputActivity.
Every Activity mentioned above is hosting a fragment. I am providing the activity code below.
ReadingActivity
public class ReadingActivity extends BaseAppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if( savedInstanceState == null ) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, ReadingFragment.getInstance(), ReadingFragment.TAG).commit();
}
setDisplayHomeAsUpEnabled(true);
setActionBarText(getString(R.string.new_project_reading));
}
#Override
protected void setupContentView() {
setContentView(R.layout.activity_reading);
}
public static Intent newIntent(Context context) {
Intent intent = new Intent(context, ReadingActivity.class);
return intent;
}
}
NewProjectReadingActivity
public class NewProjectReadingActivity extends BaseAppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if( savedInstanceState == null ) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, NewProjectReadingFragment.getInstance(), NewProjectReadingFragment.TAG).commit();
}
setDisplayHomeAsUpEnabled(true);
setActionBarText(getString(R.string.new_project_reading));
}
#Override
protected void setupContentView() {
setContentView(R.layout.activity_new_project_reading);
}
public static Intent newIntent(Context context) {
Intent intent = new Intent(context, NewProjectReadingActivity.class);
return intent;
}
}
ReadingInputActivity
public class ReadingInputActivity extends BaseAppCompatActivity {
private static final String EXTRA_VALUE_TYPE = "value_type";
private int valueType = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
valueType = getIntent().getIntExtra(EXTRA_VALUE_TYPE, 0);
if( savedInstanceState == null ) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, ReadingInputFragment.getInstance(valueType), ReadingInputFragment.TAG).commit();
}
setDisplayHomeAsUpEnabled(true);
setActionBarText(getString(R.string.reading_input));
}
#Override
protected void setupContentView() {
setContentView(R.layout.activity_reading_input);
}
public static Intent newIntent(Context context, int valueType) {
Intent intent = new Intent(context, ReadingInputActivity.class);
intent.putExtra(EXTRA_VALUE_TYPE, valueType);
return intent;
}
}
ReadingConfirmationActivity
public class ReadingConfirmationActivity extends BaseAppCompatActivity {
private static final String EXTRA_VALUE_TYPE = "value_type";
private static final String EXTRA_READING_VALUE = "reading_value";
private int valueType = 0;
private double readingValue = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
valueType = getIntent().getIntExtra(EXTRA_VALUE_TYPE, 0);
readingValue = getIntent().getDoubleExtra(EXTRA_READING_VALUE, 0);
if( savedInstanceState == null ) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, ReadingConfirmationFragment.getInstance(valueType, readingValue), ReadingConfirmationFragment.TAG).commit();
}
setDisplayHomeAsUpEnabled(true);
setActionBarText(getString(R.string.reading_input));
}
#Override
protected void setupContentView() {
setContentView(R.layout.activity_reading_confirmation);
}
public static Intent newIntent(Context context, int valueType, double readingValue) {
Intent intent = new Intent(context, ReadingConfirmationActivity.class);
intent.putExtra(EXTRA_VALUE_TYPE, valueType);
intent.putExtra(EXTRA_READING_VALUE, readingValue);
return intent;
}
}
You wrote:
What i want is that if the user selects Option Two on the
ReadingConfirmationActivity then the user will be taken to the
NewReadingActivity that means i want to remove
ReadingConfirmationActivity (which is easy just call the finish()) and
the activity started before that activity i,e ReadingInputActivity.
To do this you will do the following when the user selects Option Two in ReadingConfirmationActivity:
Intent intent = new Intent(this, NewReadingActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
This will cause all of the activities on top (and including) NewReadingActivity to be finished. A new instance of NewReadingActivity will be created and shown to the user. If you wish to return to the existing instance of NewReadingActivity, you can also do that by also adding Intent.FLAG_ACTIVITY_SINGLE_TOP to the Intent.

Send parcelable object from second_activiy to main_activity, is it possible?

I´m trying to send a parcelabe object from second activity to main activity, but the main activity is still in the Activities´ Stack, so I have two main activity running, I know this because I have a button to close the app and I have to press the button twice, one per each main activity.
Is it possible to send a parcelable object to main activity without open again the main activity? Is it impossible or I must use sql Lite instead of?
Is other command to use instead of startActivity() to call an activity that is now in the activities stack?
My goal saves in a list the new document that the user has saved in the second activity and shown it in the main activity all the documents save.
I can recover the data send for the second activity to the main activity, but I have two main activity running...
Any advice?
Thanks in advance.
My code:
public class Albaran implements Parcelable {
private String numalbaran;
private boolean tienefoto;
private boolean incidencia;
private Uri imageToUploadUri;
public Albaran(){
}
public Albaran(String numalbaran, boolean tienefoto, boolean incidencia, Uri imageToUploadUri) {
this.numalbaran = numalbaran;
this.tienefoto = tienefoto;
this.incidencia = incidencia;
this.imageToUploadUri = imageToUploadUri;
}
protected Albaran(Parcel in) {
numalbaran = in.readString();
tienefoto = in.readByte() != 0;
incidencia = in.readByte() != 0;
imageToUploadUri = in.readParcelable(Uri.class.getClassLoader());
}
public static final Creator<Albaran> CREATOR = new Creator<Albaran>() {
#Override
public Albaran createFromParcel(Parcel in) {
return new Albaran(in);
}
#Override
public Albaran[] newArray(int size) {
return new Albaran[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(numalbaran);
dest.writeByte((byte) (tienefoto ? 1 : 0));
dest.writeByte((byte) (incidencia ? 1 : 0));
dest.writeParcelable(imageToUploadUri, flags);
}
}
I call to the second activity in my main activity
public void recogerDatos(View view){ //Onclick
intent = new Intent(this,RecogerActivity.class);
startActivity(intent);
}
I call to the first activity from my second activity
public void guardarAlbaran(View view){ //Save data when button is pressed
Albaran NuevoAlbaran = new Albaran(numAlbaran.toString(),incidenciaCheckbox.isChecked(), incidenciaCheckbox.isChecked(), imageToUploadUri);
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("Albaran", NuevoAlbaran);
startActivity(intent);
finish(); //Finalizar Actividad
}
I read the data from the parcelable objects in my main activity
Albaran nuevoAlbaran;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nuevoAlbaran = getIntent().getParcelableExtra("Albaran");
}

starting activity from itself skips the OnCreate

I have this activity which is called MainPutShipActivity and I want to start it again so it will do the same thing but it doesn't even enter the OnCreate method.
here is the MainPutShipActivity:
public class MainPutShipActivity extends Activity implements OnClickListener{
private static final int MAX = 10;
private String name1,name2;
private Player plr = new Player();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_put_ship);
Intent intent = getIntent();
plr = (Player) intent.getSerializableExtra("player");
name1 = plr.getName1();
name2 = plr.getName2();
}
public void finished() {
Intent in;
}
if (plr.isTreated() == false) {
plr.setArr1(arr);
plr.setShip1(ships);
this.finish();
in = new Intent(this,MainPutShipActivity.class);
in.putExtra("player", this.plr);
}
else {
plr.setArr2(arr);
plr.setShip2(ships);
in = new Intent(this, MainGameActivity.class);
in.putExtra("player", this.plr);
}
plr.setTreated(true);
this.finish();
startActivity(in);
}
When i enter the finished() procedure for the first time it suppose to start the MainPutShipActivity again but when it starts the activity, it skips the onCreate and goes straight to the finished() method for some reason.
I would be very glad for any kind of help.
Pay attention to the key passed in the intent
Instead of :
plr = (Player) i.getSerializableExtra("plr");
set
plr = (Player) i.getSerializableExtra("player");
because you are setting
in.putExtra("player", this.plr);

How to use notifyDataSetChanged with finish()

I have a list view which show list of task, on selecting task it shows details about task, when I delete the particular task it returns to the previous activity by finish(). but it does not update the list.
I want to know how and where to use notifyDataSetChanged method and add adapter method is never used.
Other than notifyDataSetChanged() solution is also accepted :) i just want to update the list when it returns to the previous activity.
Do it with startActivityForResult(). When you create intent to open new activity open it for result. The task being deleted is your result. So when it's marked as deleted and you return to your previous activity, the result triggers and you can delete the marked item + call the notify.
More info here : http://developer.android.com/training/basics/intents/result.html
you can use the notifyDataSetChanged on the onResume method, this always update the data itself when the Activity shows
You can also notify your parent activity before finishing your current activity. You just have to register a Receiver in your main activity and all others activities will be able to notify that activity. You can even send data!
As my english is not that good, sample code :
The MainActivity class
public class MainActivity extends AppCompatActivity {
// you can define your name for your receiver as a constant,
// so you can access it from other activities if you want
public static final String MY_SUPER_INTERNAL_NOTIFICATION = "MY_SUPER_INTERNAL_NOTIFICATION";
public static final String MY_OBJECT = "my_object";
public static final String MY_OBJECT_POSITION = "my_object_position" ;
private MyCustomAdapter adapter;
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(R.id.listView);
// set up your list with your adapter and data...
adapter = new MyCustomAdapter(this);
// [...] I suppose you know how to do that, I dont write everything
listView.setAdapter(adapter);
// when you click on a row from your list,
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(
MainActivity.this,
SecondActivity.class
);
// you can for example put data in a Bundle and pass it to the other activity
// then on the onCreate you can use that data as you want
Bundle bundle = new Bundle();
// IMPORTANT be sure that the object you are putting in the bundle is Serializable (implements Serializable)
bundle.putSerializable(MY_OBJECT, adapter.getItem(position));
// you can also for example send the position of the row you clicked
bundle.putInt(MY_OBJECT_POSITION, position);
// put your bundle in the intent
intent.putExtras(bundle);
startActivity(intent);
}
});
// register your Receiver! don't forget to do that or you will never be notified
LocalBroadcastManager
.getInstance(this)
.registerReceiver(
broadcastReceiver,
new IntentFilter(MY_SUPER_INTERNAL_NOTIFICATION)
);
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent != null) {
// get the position sent by the other activity
int position = intent
.getExtras()
.getInt(SecondActivity.MY_EXAMPLE_KEY);
adapter.deleteItem(position);
}
}
};
// adapter class...
private class MyCustomAdapter extends BaseAdapter {
ArrayList<MyObject> data;
public MyCustomAdapter(Context context) {
}
public void deleteItem(int position){
// delete your item from the list of data
data.remove(position);
// dont forget to notify
notifyDataSetChanged();
}
#Override
public int getCount() {
return 0;
}
#Override
public MyObject getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
return null;
}
// adapter class, you can extend your favorite type of adapter
}
}
The SecondActivity class :
public class SecondActivity extends AppCompatActivity {
public static final String MY_EXAMPLE_KEY = "EXAMPLE";
private MyObject myObject;
private int myObjectPosition;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
myObject = (MyObject) getIntent()
.getExtras()
.getSerializable(MainActivity.MY_OBJECT);
myObjectPosition = getIntent()
.getExtras()
.getInt(MainActivity.MY_OBJECT_POSITION);
// do all your stuff with your object
// before calling finish do this
beforeFinishDoThisStuff();
}
private void beforeFinishDoThisStuff() {
sendBroadcastToMainActivity();
finish();
}
private void sendBroadcastToMainActivity() {
// create an intent and put your Receiver name as action name
// like you defined in your MainActivity
Intent intent = new Intent(MainActivity.MY_SUPER_INTERNAL_NOTIFICATION);
Bundle bundle = new Bundle();
// put whatever you want, here I put just the previous position of the object in the list
bundle.putInt(MY_EXAMPLE_KEY, myObjectPosition);
intent.putExtras(bundle);
// notify your MainActivity
LocalBroadcastManager
.getInstance(this)
.sendBroadcast(intent);
// after this finish !
}
}
Hope you understand how to notify activities with BroadcastManager. It's very powerful and simple to use.
Have fun coding !

Passing Object with multiple parts from one activity to another

Hi I have a Requirement like Person Details for that i have multiple details like personal,educational,job like In first activity am enter personal details and then educational and then job like that one after another for that how can i maintain all details in single object and pass through app please help me.
Be aware that you need to bundle an object in an Intent, that object must implement the Parcelable interface. Here's a common implementation taken from the Parcelable documentation...
public class MyParcelable implements Parcelable {
private int mData;
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeInt(mData);
}
public static final Parcelable.Creator<MyParcelable> CREATOR
= new Parcelable.Creator<MyParcelable>() {
public MyParcelable createFromParcel(Parcel in) {
return new MyParcelable(in);
}
public MyParcelable[] newArray(int size) {
return new MyParcelable[size];
}
};
private MyParcelable(Parcel in) {
mData = in.readInt();
}
}
Once you've done that, simply pass the object around in an Intent...
Intent i = new Intent(getApplicationContext(), ACTIVITY_TO_START.class);
i.putExtra("extra_key", new MyParcelable());
startActivity(i);
to retrieve the object for the starting activity...
Bundle extras = getIntent().getExtras();
if(extras != null && extras.containsKey("extra_key"))
{
MyParcelable p = (MyParecelable)extras.getParcelable("extra_key");
}
Simple solution: Use intents for this
Personal.class
public class Personal extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.personal);
Intent i = new Intent(getApplicationContext(), Educational.class);
i.putExtra("personal_details",<-get data from object->);
startActivity(i);
}
}
Educational.class
public class Personal extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.personal);
String personal_details;
Bundle extras = getIntent().getExtras();
if (extras != null) {
personal_details= extras.getString("personal_details");
}
Intent i = new Intent(getApplicationContext(), educational.class);
i.putExtra("personal_details",personal_details);
i.putExtra("educational_details",<-get data from object->);
startActivity(i);
}
}
Job.class
public class Personal extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.personal);
String personal_details,educational_details;
Bundle extras = getIntent().getExtras();
if (extras != null) {
personal_details= extras.getString("personal_details");
educational_details= extras.getString("educational_details");
}
Intent i = new Intent(getApplicationContext(), FinalResult.class);
i.putExtra("personal_details",personal_details);
i.putExtra("educational_details",educational_details);
i.putExtra("job_details",<-get data from object->);
startActivity(i);
}
}
FinalResult.class
public class Personal extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.personal);
String personal_details,educational_details,job_details;
Bundle extras = getIntent().getExtras();
if (extras != null) {
personal_details= extras.getString("personal_details");
educational_details= extras.getString("educational_details");
job_details= extras.getString("job_details");
}
}
}
{EDIT-1}
have a look at one of my answers in different storage options in
android - Click Here
You can achieve it using application variable or shared
preferences but i would not recommend it. !
Try storing it in POJO(Plain old Java class)
{EDIT-2}
Hmm if i understand correctly your question:: You are connected to internet(Wifi,Wired,... etc) basically you are trying to show a dialog when there is no network connectivity ! .... You can take the help of Broadcast receivers ...
Try this:: Set the broadcast receiver to fire the intent when there is no net connectivity ....
Write the code to catch that intent and pop the dialog .... In this dialog give the user option to reconnect the connectivity !

Categories

Resources